Imagine this, you are testing a Rails application with RSpec and you have the need to freeze or travel through time in your specs. Your old trusted friend Timecop has served you well in the past but you’ve heard about this new kid in Rails 4.1, ActiveSupport::Testing::TimeHelpers. You decide not having to pull in another dependency is a good thing and decide to use the new kid on the block. You write your first test:
require 'spec_helper' describe SomeObject do it 'works with the new hotness' do the_thing = SomeObject.new travel_to(1.day.ago) do expect(the_thing.works_with_new_hotness?).to eq true end end end
When you run your test, you get the dreaded NoMethodError: undefined method `travel’ for #<RSpec::Core::ExampleGroup::Nested_1:0x007fa7067e8f10> error. How do you fix it you ask? You include ActiveSupport::Testing::TimeHelpers into your test:
require 'spec_helper' describe SomeObject do include ActiveSupport::Testing::TimeHelpers it 'works with the new hotness' do the_thing = SomeObject.new travel_to(1.day.ago) do expect(the_thing.works_with_new_hotness?).to eq true end end end
Another option is to include that module in all of your tests:
RSpec.configure do |config| .... config.include ActiveSupport::Testing::TimeHelpers .... end
Travel safely!
About the Author