Rspec 在哈希中的时间戳出现问题

Sur*_*rya 3 ruby rspec ruby-on-rails rspec-rails

为了与 hashdata 进行比较,我们在规范中有这个

it 'should return the rec_1 in page format' do
     expect(response_body_json).to eql(Preseneter.new(ActiveRecordObject).page)
end
Run Code Online (Sandbox Code Playgroud)

Presenter 是一个类,它将接受 ActiveRecordObject 并以特定格式响应哈希数据。

然后我们将带有时间戳的updated_at 添加到hash_data 中。 在我的代码中,我有updated_at = Time.zone.now 所以规范开始失败,因为两个 Updated_at 都有几秒钟的差异。

尝试存根时区

it 'should return the rec_1 in page format' do
     allow(Time.zone).to receive(:now).and_return('hello')
     expect(response_body_json).to eql(Preseneter.new(ActiveRecordObject).page)
end
Run Code Online (Sandbox Code Playgroud)

但现在response_body_json.updated_at作为“hello”出现,但右侧仍然带有时间戳

我哪里错了???或者还有其他更好的方法来处理这种情况吗?

Tom*_*ord 5

因为你还没有展示如何response_body_json定义也Presenter#page没有定义,我无法真正回答为什么您当前的尝试不起作用。

然而,我可以说我会使用不同的方法。

有两种标准方法可以编写这样的测试:

  1. 冻结时间

假设您使用的是相对最新的 Rails 版本,您可以ActiveSupport::Testing::TimeHelpers#freeze_time在测试中的某个地方使用 use ,例如:

around do |example|
  freeze_time { example.run }
end

it 'should return the movie_1 in page format' do
  expect(response_body_json).to eql(Presenter.new(ActiveRecordObject).page)
end
Run Code Online (Sandbox Code Playgroud)

如果您使用的是较旧的 Rails 版本,您可能需要使用travel_to(Time.zone.now)

如果您使用的是非常旧的 Rails 版本(或非 Rails 项目!),它没有这个帮助程序库,您可以使用它timecop

  1. 对时间戳使用模糊匹配器(例如be_within)。大致如下:

it 'should return the movie_1 in page format' do
  expected_json = Presenter.new(ActiveRecordObject).page
  expect(response_body_json).to match(
    expected_json.merge(updated_at: be_within(3.seconds).of(Time.zone.now))
  )
end
Run Code Online (Sandbox Code Playgroud)