在Capybara测试中盯着时间

时间:2014-09-28 18:22:40

标签: ruby-on-rails selenium capybara stubbing

我有一个页面可以创建文档的快照。保存该文档时标题为时间戳(September 27, 2014 at 4:01:10 pm)。我正在为这个页面编写一个测试,并希望将时间存储起来,以便它不会发生变化。

我目前所拥有的是Time.stubs(:now).returns(Time.parse("2014-1-2 11:00:00")),但当我这样做时,我收到一条错误消息:

  

Capybara :: FrozenInTime:时间似乎被冻结,Capybara不与冻结时间的图书馆合作,考虑使用时间旅行

在这里留出时间的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

Rails现在直接includes support进行时间旅行,例如:

feature 'Time travel verifier' do
  include ActiveSupport::Testing::TimeHelpers

  scenario 'works in the past' do
    travel_to(1.day.ago) do
      visit time_travel_verification_path
      expect(page).to have_content('WOAH Time Travel!')
    end
  end
end

答案 1 :(得分:0)

我将此评论作为答案重新发布。

timecop gem https://github.com/travisjeffery/timecop

它允许您执行以下操作:

describe "some set of tests to mock" do
  before do
    Timecop.freeze(Time.local(1990))
  end

  after do
    Timecop.return
  end

 it "should do blah blah blah" {}
end

这将使测试像1990-1-1一样运行,然后返回到当前时间。