比较时间与RSpec的故障 [英] Trouble comparing time with RSpec
问题描述
我使用Ruby on Rails 4和rspec-rails gem 2.14。对于我的对象,我想在控制器动作运行之后,将当前时间与 updated_at
对象属性进行比较,但是我遇到麻烦,因为规范没有通过。也就是说,下面是规范代码:
I am using Ruby on Rails 4 and the rspec-rails gem 2.14. For a my object I would like to compare the current time with the updated_at
object attribute after a controller action run, but I am in trouble since the spec does not pass. That is, given the following is the spec code:
it "updates updated_at attribute" do
Timecop.freeze
patch :update
@article.reload
expect(@article.updated_at).to eq(Time.now)
end
当我运行上面的规范,我得到以下错误:
When I run the above spec I get the following error:
Failure/Error: expect(@article.updated_at).to eq(Time.now)
expected: 2013-12-05 14:42:20 UTC
got: Thu, 05 Dec 2013 08:42:20 CST -06:00
(compared using ==)
如何让规格通过?
:我也尝试了以下(注意 utc
添加):
it "updates updated_at attribute" do
Timecop.freeze
patch :update
@article.reload
expect(@article.updated_at.utc).to eq(Time.now)
end
但规格仍然不通过注意got值差异):
but the spec still does not pass (note the "got" value difference):
Failure/Error: expect(@article.updated_at.utc).to eq(Time.now)
expected: 2013-12-05 14:42:20 UTC
got: 2013-12-05 14:42:20 UTC
(compared using ==)
推荐答案
精度比数据库做的。当从数据库读回值时,它只保留到微秒精度,而内存中的表示精确到纳秒。
Ruby Time object maintains greater precision than the database does. When the value is read back from the database, it’s only preserved to microsecond precision, while the in-memory representation is precise to nanoseconds.
如果你不在乎毫秒的差异,你可以在你的期望的两边做一个to_s / to_i
If you don't care about millisecond difference, you could do a to_s/to_i on both sides of your expectation
expect(@article.updated_at.utc.to_s).to eq(Time.now.to_s)
或
expect(@article.updated_at.utc.to_i).to eq(Time.now.to_i)
请参阅此有关时间不同的更多信息
Refer to this for more information about why the times are different
这篇关于比较时间与RSpec的故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!