【发布时间】:2014-05-03 14:55:54
【问题描述】:
在我的测试套件中,我的测试失败了。
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
>
这怎么可能?
我试图重现这个问题(我认为 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
编辑:更多测试...
> 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"
看起来比较是基于散列对象的。为什么 res 和 expected 有不同的 hashes ?
【问题讨论】:
-
什么是 res ?你试过打印 res.inspect 和 expected.inspect 吗?
-
@vdaubry 添加了检查
-
遇到同样的问题 - 你解决了吗?
-
在测试时添加了几个不同的答案来解决这个问题,不确定它们中的任何一个是否对每个人都有用,但我能够在回答 #2 (Spring/Rspec) 之后解决我的问题.
标签: ruby-on-rails ruby-on-rails-3 timezone activesupport