我使用的是Ruby on Rails 4和rspec-rails gem 2.14。对于my对象,我希望在控制器操作运行后将当前时间与updated_at
对象属性进行比较,但我遇到了麻烦,因为规范没有通过。也就是说,给定以下规范代码:
it "updates updated_at attribute" do
Timecop.freeze
patch :update
@article.reload
expect(@article.updated_at).to eq(Time.now)
end
当我运行上面的规范时,我得到了以下错误:
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“值的差异):
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 ==)
发布于 2013-12-05 22:59:34
Ruby Time对象比数据库保持更高的精度。当从数据库读回值时,它只保留到微秒精度,而内存中的表示精确到纳秒。
如果你不关心毫秒差,你可以在你期望的两边做一个to_s/to_i
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)
有关时间不同原因的详细信息,请参阅this
发布于 2014-10-06 05:24:26
我发现使用be_within
默认的rspec匹配器更优雅:
expect(@article.updated_at.utc).to be_within(1.second).of Time.now
发布于 2015-04-09 01:10:14
老帖子,但我希望它能帮助任何进入这里寻找解决方案的人。我认为手动创建日期更简单、更可靠:
it "updates updated_at attribute" do
freezed_time = Time.utc(2015, 1, 1, 12, 0, 0) #Put here any time you want
Timecop.freeze(freezed_time) do
patch :update
@article.reload
expect(@article.updated_at).to eq(freezed_time)
end
end
这确保了存储的日期是正确的,而无需执行to_x
或担心小数。
https://stackoverflow.com/questions/20403063
复制相似问题