31

I just tried to use Rails' time helper method travel in one of my feature specs:

scenario 'published_at allows to set a publishing date in the future' do
  magazine_article.update_attribute(:published_at, Time.now + 1.day)
  expect { visit magazine_article_path(magazine_article.magazine_category, magazine_article) }
         .to raise_error(ActiveRecord::RecordNotFound)

  travel 2.days do
    visit magazine_article_path(magazine_article.magazine_category, magazine_article)
    expect(page).to have_content('Super awesome article')
  end
end 

It's giving me this:

NoMethodError:
   undefined method `travel' for #<RSpec::ExampleGroups::MagazineArticles::AsUser::Viewing:0x007f84a7a95640>

What am I missing?

http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Flip
  • 6,233
  • 7
  • 46
  • 75

2 Answers2

55

In order to use these helpers you have to include them into your tests.

You can do this by either including it into single test suite:

describe MyClass do
  include ActiveSupport::Testing::TimeHelpers
end

or globally:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • 11
    Don't forget to require the file `require 'active_support/testing/time_helpers'` – MegaTux May 21 '18 at 14:03
  • Does anyone know if there is a typical reason why one would not want to have it included globally? – kluka Jul 25 '19 at 10:05
  • 1
    @kluka its good practice to only use what you actually need. The more code you require the slower it gets. I often don't need the time helpers at all, or maybe only later in only specific places. – Robin Aug 17 '22 at 09:20
4

Following on @andrey-deineko...

I created a file time_helpers.rb under spec\support as follows:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end
Jon Kern
  • 3,186
  • 32
  • 34