Date与ActiveSupport :: TimeWithZone的比较失败

Kyl*_*cot 17 ruby unit-testing rspec ruby-on-rails ruby-on-rails-3

我的模型age上有一个方法Waiver,如下所示:

  def age(date = nil)

    if date.nil?
      date = Date.today
    end
    age = 0
    unless date_of_birth.nil?
      age = date.year - date_of_birth.year
      age -= 1 if date < date_of_birth + age.years #for days before birthday
    end
    return age
  end
Run Code Online (Sandbox Code Playgroud)

然后,我有一个看起来像这样的规范:

it "calculates the proper age" do
 waiver = FactoryGirl.create(:waiver, date_of_birth: 12.years.ago)
 waiver.age.should == 12
end
Run Code Online (Sandbox Code Playgroud)

当我运行这个规范时,我得到了comparison of Date with ActiveSupport::TimeWithZone failed.我究竟做错了什么?

Failures:

  1) Waiver calculates the proper age
     Failure/Error: waiver.age.should == 12
     ArgumentError:
       comparison of Date with ActiveSupport::TimeWithZone failed
     # ./app/models/waiver.rb:132:in `<'
     # ./app/models/waiver.rb:132:in `age'
     # ./spec/models/waiver_spec.rb:23:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

ros*_*sta 37

您正在将实例DateActiveSupport::TimeWithZone表达式中的实例进行比较date < date_of_birth + age.years; 根据文档,ActiveSupport :: TimeWithZone是一个类似时间的类,可以表示任何时区的时间.如果不执行某种转换,您无法比较DateTime对象.试试Date.today < Time.now控制台; 你会看到类似的错误.

表达式12.years.ago和典型的ActiveRecord时间戳是ActiveSupport :: TimeWithZone的实例.您最好确保只处理Time对象或Date对象,但不能同时处理这两种方法.为了使您的比较与日期相比,表达式可以写成:

age -= 1 if date < (date_of_birth + age.years).to_date
Run Code Online (Sandbox Code Playgroud)