Move Over Timecop…Hello ActiveSupport::Testing::TimeHelpers

May 15, 2014 Mike Gehard

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

Biography

More Content by Mike Gehard
Previous
Wrapping Objective-C Delegates with Blocks, Part 1
Wrapping Objective-C Delegates with Blocks, Part 1

Since adding blocks to Objective-C, Apple has designed more and more of their APIs to use them as the prefe...

Next
Pivotal People—Janne Valkealahti , Spring YARN Master and Open Source Software Engineer
Pivotal People—Janne Valkealahti , Spring YARN Master and Open Source Software Engineer

Spring YARN is possibly one of the coolest projects on planet earth these days. Come meet Janne Valkealahti...