两个 ActiveSupport::TimeWithZone 对象之间的比较失败

Ben*_*ier 5 timezone ruby-on-rails activesupport ruby-on-rails-3

在我的测试套件中,我有一个失败的测试。

expected[0]['date']来自SomeModel.first.created_at

在调试控制台中,我有以下内容:

> expected[0]['date']
=> Tue, 25 Mar 2014 16:01:45 UTC +00:00
> res[0]['date']
=> Tue, 25 Mar 2014 16:01:45 UTC +00:00
> res[0]['date'] == expected[0]['date']
=> false # wtf
> res[0]['date'].class
=> ActiveSupport::TimeWithZone
> expected[0]['date'].class
=> ActiveSupport::TimeWithZone
>
Run Code Online (Sandbox Code Playgroud)

这怎么可能 ?

我试图重现这个问题(我认为 TimeWithZone 上的 == 运算符可能会检查引用,或者类似的东西,但没有......):

> t1 = Time.zone.at(0)
=> Thu, 01 Jan 1970 00:00:00 UTC +00:00
> t2 = Time.zone.parse(t1.to_s)
=> Thu, 01 Jan 1970 00:00:00 UTC +00:00
> t1 == t2
=> true
> t1.class
=> ActiveSupport::TimeWithZone
> t2.class
=> ActiveSupport::TimeWithZone
Run Code Online (Sandbox Code Playgroud)

编辑:更多测试...

> res[0]['date'].eql?(expected[0]['date'])
=> false
> res[0]['date'].zone
=> "UTC"
> expected[0]['date'].zone
=> "UTC"
> expected[0]['date'].getlocal
=> 2014-03-25 16:01:45 +0000
> res[0]['date'].getlocal
=> 2014-03-25 16:01:45 +0000
> res[0]['date'].hash
=> -3455877575500291788
> expected[0]['date'].hash
=> -3819233736262144515
>
> t1.hash
=> 2279159074362527997
> t2.hash
=> 2279159074362527997

# inspect...
> expected[0]['date'].inspect
=> "Tue, 25 Mar 2014 16:39:01 UTC +00:00"
> res[0]['date'].inspect
=> "Tue, 25 Mar 2014 16:39:01 UTC +00:00"
Run Code Online (Sandbox Code Playgroud)

看起来比较是基于哈希对象的。为什么 res 和预期有不同的hashes ?

Kur*_*nai 1

答案#1 rake db:test:prepare

首先,尝试删除测试数据库并重新创建它,然后运行rake db:test:prepare​​. 这在过去已经为我解决了这个问题,我知道这有点蹩脚的答案,但值得一试。

答案 #2 Spring + Rspec + Shoulda 匹配器

如果安装Spring后遇到此问题,请查看此 Github 线程,这可能会导致测试失败: https: //github.com/rails/spring/issues/209

在将 Spring 添加到我的项目后,这个问题才开始出现。添加gem 'shoulda', require: false并手动添加require 'shoulda/matchers'到我spec_helper.rb解决的问题

答案 #3时间警察

如果仍有问题,请查看 Timecop gem 并冻结日期比较的时间。 https://github.com/travisjeffery/timecop