与Rspec麻烦的哈希时间戳

露娜·洛夫古德(Luna Lovegood)

为了与哈希数据进行比较,我们在规范中有了

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

Presenter是一个类,它将接受ActiveRecordObject并使用特定格式的哈希数据进行响应。

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

尝试存根Time.zone

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

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

我要去哪里错了???还是有其他更好的方法来处理这种情况?

汤姆·洛德

既然你还没有表现出怎样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

如果您使用的是较旧的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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章