【问题标题】:Comparison between two ActiveSupport::TimeWithZone objects fails两个 ActiveSupport::TimeWithZone 对象之间的比较失败
【发布时间】: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


【解决方案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

【讨论】:

  • 似乎错误来自比较#to_f的结果,我只使用 aligned 时间戳和我的测试,例如1.day.ago.noon 我猜timecop会做类似的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
相关资源
最近更新 更多