Date与ActiveSupport :: TimeWithZone的比较失败
我的Waiver
模型上有一个age
方法,如下所示:
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 '
您正在将Date
的实例与表达date < date_of_birth + age.years
的ActiveSupport::TimeWithZone
实例进行比较; 根据文档 ,ActiveSupport :: TimeWithZone是一个类似时间的类,可以表示任何时区的时间。 您无法在不执行某种转换的情况下比较Date
和Time
对象。 在控制台上尝试Date.today < Time.now
; 你会看到类似的错误。
12.years.ago
和典型的ActiveRecord时间戳等表达式是ActiveSupport :: TimeWithZone的实例。 最好确保只处理Time
对象或Date
对象,但不能同时处理这两种方法。 为了使您的比较与日期相比,表达式可以写成:
age -= 1 if date < (date_of_birth + age.years).to_date
- 为什么我不建议“在全球范围内包括Capybara :: DSL!”
- 如何使用Rspec在Sinatra中测试助手块?
- WebMock模拟失败的API(没有互联网,超时++)
- 如何使用Rspec测试使用Paperclip的模型是否validation上传文件的大小?
- *** RuntimeErrorexception:ActionView :: Helpers :: ControllerHelper#response委托给controller.response,但是控制器是nil
- 运行我的控制器的rspec测试时出现Rspec错误
- rspec-rails和使用let导致变量冲突?
- 使用Rspec + Capybara在Rails中测试错误页面
- 如何在rspec测试中定义一个可以由辅助函数接收的简单全局变量