无法将时间与 RSpec 进行比较 [英] Trouble comparing time with RSpec

查看:24
本文介绍了无法将时间与 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 ==)

我怎样才能让规范通过?

How can I make the spec to pass?

注意:我也尝试了以下(注意 utc 添加):

Note: I tried also the following (note the utc addition):

it "updates updated_at attribute" do
  Timecop.freeze

  patch :update
  @article.reload
  expect(@article.updated_at.utc).to eq(Time.now)
end

但规范仍然没有通过(注意获得"的价值差异):

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 对象比数据库保持更高的精度.当该值从数据库读回时,它只保留到微秒级精度,而内存中的表示精确到纳秒级.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆