Ruby on rails 将日期与ActiveSupport::TimeWithZone进行比较失败
我在我的Ruby on rails 将日期与ActiveSupport::TimeWithZone进行比较失败,ruby-on-rails,ruby,ruby-on-rails-3,unit-testing,rspec,Ruby On Rails,Ruby,Ruby On Rails 3,Unit Testing,Rspec,我在我的豁免模型上有一个年龄方法,看起来像: 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
豁免
模型上有一个年龄
方法,看起来像:
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
当我运行这个规范时,我得到了日期与ActiveSupport::TimeWithZone的比较失败。我做错了什么
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)>'
故障:
1) 豁免计算适当的年龄
失败/错误:弃权.age.should==12
参数错误:
将日期与ActiveSupport::TimeWithZone进行比较失败
#/app/models/弃权。rb:132:在`中,您正在将日期的实例与表达式日期
中的活动支持::TimeWithZone
的实例进行比较;TimeWithZone是一个类似时间的类,可以表示任何时区中的时间。如果不执行某种转换,就无法比较日期
和时间
对象。在控制台上尝试Date.today
;您将看到类似的错误
像12.years.ago
这样的表达式和典型的ActiveRecord时间戳都是ActiveSupport::TimeWithZone的实例。最好确保只处理时间
对象或日期
对象,但不能同时处理这两个对象。要使比较日期为最新,表达式可以改为:
age -= 1 if date < (date_of_birth + age.years).to_date
age-=1,如果日期<(出生日期+年龄年)。到日期
我不知道它为什么会失败,但如果您将出生日期设置为12年前而不是12年前,它工作正常。感谢您的深入解释。我已经对代码做了适当的修改,现在一切都很好!实际上,您可以将Date与TimeWithZone进行比较,但Rails似乎会在默认情况下将Date转换为00:00:00UTC,这可能会引入错误。Ie.>Time.zone.parse('2017年8月1日星期二00:00:00 CEST+02:00')
=>true