【问题标题】:Date.today.to_s(:long) not converting to stringDate.today.to_s(:long) 未转换为字符串
【发布时间】:2020-05-07 12:07:17
【问题描述】:

我正在做一个作业,我根据我们的说明编写了以下方法:

def create_todolist(params)
    due_date = Date.today.to_s(:long)
    TodoList.create(list_name: params[:name],list_due_date: params[:due_date])
end

但是当我运行 rspec 测试时,我收到以下错误:

1) Assignment rq03 rq03.2 assignment code has create_todolist method should create_todolist with provided parameters
     Failure/Error: expect(testList.list_due_date).to eq due_date

       expected: Thu, 07 May 2020
            got: "2020-05-07"

       (compared using ==)

       Diff:
       @@ -1,2 +1,2 @@
       -Thu, 07 May 2020
       +"2020-05-07"

     # ./spec/assignment_spec.rb:177:in `block (4 levels) in <top (required)>'
     # ./spec/assignment_spec.rb:14:in `block (2 levels) in <top (required)>'

这是 rspec 测试:

context "rq03.2 assignment code has create_todolist method" do
        it { is_expected.to respond_to(:create_todolist) } 
        it "should create_todolist with provided parameters" do
            expect(TodoList.find_by list_name: "mylist").to be_nil
            due_date=Date.today
            assignment.create_todolist(:name=> 'mylist', :due_date=>due_date)
            testList = TodoList.find_by list_name: 'mylist'
            expect(testList.id).not_to be_nil
            expect(testList.list_name).to eq "mylist"
            expect(testList.list_due_date).to eq due_date
            expect(testList.created_at).not_to be_nil
            expect(testList.updated_at).not_to be_nil
        end  
      end

起初我只有due_date = Date.today 并且遇到了同样的错误,我不知道如何解决它。我想知道是不是因为我使用的 ruby​​/rails 版本与创建课程时使用的版本不同(5 年前 -_-)。

任何帮助将不胜感激!

谢谢你:)

【问题讨论】:

  • 您的问题不清楚,因为您没有显示您的测试实际做了什么。但是已经引起了我的注意:您将Date.today.to_s(:long) 分配给本地变量due_date,但不再从该变量中读取。
  • 抱歉,我已经添加了
  • params[:due_date] 没有使用due_date。它们是两个不同的变量。另外,上面写着expected: Thu, 07 May 2020 - got: "2020-05-07可能需要手动转换一下?

标签: ruby-on-rails ruby rspec rspec-rails


【解决方案1】:

您正在尝试比较一个 Date 对象:

due_date = Date.today

使用您在创建记录时生成的字符串对象:

Date.today.to_s(:long)

如您所见,这些是不同类型的对象:

Date.today.to_s(:long)
=> "May 07, 2020"
Date.today.to_s(:long).class
=> String

Date.today
=> 2020-05-07
Date.today.class
=> Date

Date.today.to_s(:long) == Date.today
=> false

【讨论】:

  • 你好,我最初只有``` Date.today ``` 但也遇到了同样的错误。
  • 这不太可能是完全相同的错误,因为您正在处理不同类型的对象。您可以改回 Date.today 并在此处添加您收到的确切错误消息吗?
  • 嗨,我知道了!当我创建 TodoLists 表时,我没有将迁移类型指定为:date。所以默认情况下,due_date 被设置为一个字符串。
【解决方案2】:

我想通了。在创建 TodoLists 表时,我没有将迁移类型指定为 :date。所以默认情况下,due_date 被设置为一个字符串。所以我设置输入 :date 并将due_date 更改为等于:

due_date = Date.today

感谢您花时间帮助我:)

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2020-12-02
    • 2019-06-21
    • 2023-03-22
    • 2013-11-25
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多