尽管预期值和接收值之间的差异为零,为什么 RSpec 仍会抛出错误

发布于 2024-11-27 20:26:53 字数 420 浏览 0 评论 0原文

我偶尔会收到以下 RSpec 错误,并且对它是什么感到困惑:

Failure/Error: Question.all[index].created_at.should == sorted_publish_dates[index]
       expected: Tue, 02 Aug 2011 21:11:11 UTC +00:00
            got: Tue, 02 Aug 2011 21:11:11 UTC +00:00 (using ==)
       Diff:
     # ./spec/models/question_spec.rb:23:in `block (3 levels) in <top (required)>'

预期值和接收到的值似乎完全相同,因此我对为什么 RSpec 认为这是一个问题感到困惑。

I get the following RSpec error sporadically and am confused as to what it is:

Failure/Error: Question.all[index].created_at.should == sorted_publish_dates[index]
       expected: Tue, 02 Aug 2011 21:11:11 UTC +00:00
            got: Tue, 02 Aug 2011 21:11:11 UTC +00:00 (using ==)
       Diff:
     # ./spec/models/question_spec.rb:23:in `block (3 levels) in <top (required)>'

The expected and received values appear to be exactly the same so I'm confused as to why RSpec thinks it's a problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

居里长安 2024-12-04 20:26:53

您正在针对 Time.now 进行测试(我怀疑)。尽管 rspec 显示相同的时间字符串,但它在输出中不包含毫秒。设置测试时,您需要存根 Time.now,以便可以可靠地测量您实际上是在对象创建的同时进行测试。

before do
  Time.stub!(:now).and_return("2011-02-08 21:11:11")
end

You are testing against Time.now (I suspect). Even though rspec is showing the same time string it isn't including milliseconds in the output. You will need to stub Time.now when you setup the test so that you can reliably measure that your are in fact testing for the same time as the object creation.

before do
  Time.stub!(:now).and_return("2011-02-08 21:11:11")
end
寻梦旅人 2024-12-04 20:26:53

如果您想查看这些时间值的实际值,请在要求 rspec 比较它们之前通过 to_f 将它们转换为浮点数。

或者,为了获得更具可读性的值,请调用 time.xmlschema(6),它将显示微秒精度。

您可能需要重新考虑如何为测试和应用程序生成这些值。在您的应用程序中,两个时间值是否保证相同(精确到微秒)?如果是这样,您的测试是否以相同的方式生成时间?

If you want to see what those time values actually are, convert them to floats via to_f before asking rspec to compare them.

Or, for a more readable value, call time.xmlschema(6) which will display microsecond precision.

You may want to rethink how you're generating these values for the test and in your app. In your app, are the 2 time values guaranteed to be the same, down to the microsecond? If so, does your test generate the times the same way?

我ぃ本無心為│何有愛 2024-12-04 20:26:53

您的商品的 to_s 是相同的。这并不意味着这些项目是相同的。我敢打赌它们是不同类的实例。

The to_s for your items are the same. That does not mean that the items are the same. I bet that they are instances of different classes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文