特拉维斯 CI RSpec 测试。比较保持相同时间的变量
Travis CI RSpec tests. Comparing variables that hold the same time
我有这样的测试
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 someone else could
not update question
Failure/Error: 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
怎么会不一样呢??在我的本地机器上它通过了
您或许可以改进测试的结构。考虑使用模拟和存根而不是测试状态突变(或缺乏状态突变):
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
你可以使用 ActiveSupport::Testing::TimeHelpers#travel
像这样将其包含在 rails_helper.rb
中:
RSpec.configure do |config|
include ActiveSupport::Testing::TimeHelpers
...
然后在你的测试中,使用travel_to Time.now
来冻结时间。
我有这样的测试
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 someone else could not update question Failure/Error: 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
怎么会不一样呢??在我的本地机器上它通过了
您或许可以改进测试的结构。考虑使用模拟和存根而不是测试状态突变(或缺乏状态突变):
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
你可以使用 ActiveSupport::Testing::TimeHelpers#travel
像这样将其包含在 rails_helper.rb
中:
RSpec.configure do |config|
include ActiveSupport::Testing::TimeHelpers
...
然后在你的测试中,使用travel_to Time.now
来冻结时间。