Travis CI RSpec测试。比较保持相同时间的变量

时间:2016-04-09 18:13:47

标签: ruby-on-rails rspec travis-ci rspec-rails

我有这样的测试

  it 'could not update question' do
    old_title = question.title
    old_body = question.body
    old_updated_at = question.updated_at

    patch :update, id: question, question: attributes_for(:question, title: 'new valid title', body: 'new valid body'), format: :js
    question.reload

    expect(question.title).to eq old_title
    expect(question.body).to eq old_body
    expect(question.updated_at).to eq old_updated_at
  end

它引发了一个错误:

  

1)QuestionsController PATCH #update问题由别人可以   不更新问题        失败/错误:期望(question.updated_at).to eq old_updated_at

   expected: 2016-04-09 18:05:03.650576201 +0000
        got: 2016-04-09 18:05:03.650576000 +0000

怎么会有所不同?在我的本地机器上传递

2 个答案:

答案 0 :(得分:1)

您可以改进测试结构。考虑使用模拟和存根而不是测试状态突变(或缺乏突变):

it 'could not update question' do
    expect(Question).to_not receive(:update)  # Depending on how your model gets updated
    patch :update, id: question, question: attributes_for(:question, title: 'new valid title', body: 'new valid body'), format: :js
end

答案 1 :(得分:0)

您可以使用ActiveSupport::Testing::TimeHelpers#travel

将其包含在rails_helper.rb中,如下所示:

RSpec.configure do |config|
include ActiveSupport::Testing::TimeHelpers
...

然后在测试中,使用travel_to Time.now来冻结时间。