我有一个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
然后我有一个看起来像这样的规范:
it "calculates the proper age" do
waiver = FactoryGirl.create(:waiver, date_of_birth: 12.years.ago)
waiver.age.should == 12
end
当我运行这个规范时我得到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)>'
您正在比较一个实例Date
与一个实例ActiveSupport::TimeWithZone
在表达式中date < date_of_birth + age.years
; ActiveSupport::TimeWithZone 是,根据文档 http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html,一个类似 Time 的类,可以表示任何时区的时间。你根本无法比较Date
and Time
对象而不执行某种转换。尝试Date.today < Time.now
在控制台上;你会看到类似的错误。
表达如12.years.ago
典型的 ActiveRecord 时间戳是 ActiveSupport::TimeWithZone 的实例。你最好确保你只处理Time
物体或Date
对象,但不能同时出现在该方法中。为了使比较是最新的,表达式可以写成:
age -= 1 if date < (date_of_birth + age.years).to_date
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)