【问题标题】:Travis CI RSpec tests. Comparing variables that hold the same timeTravis CI RSpec 测试。比较保持相同时间的变量
【发布时间】:2016-04-09 18:13:47
【问题描述】:

我有这样的测试

  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 by others could 不更新问题 失败/错误:expect(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

怎么会不一样??在我的本地机器上它通过了

【问题讨论】:

  • 经验法则:永远不要相信浮点数

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


【解决方案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

【讨论】:

    【解决方案2】:

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

    像这样将它包含在rails_helper.rb 中:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      相关资源
      最近更新 更多