KatPadi's Point

How To Time Travel Using ActiveSupport TimeHelpers

So I needed to test “time”…quite literally. I needed to test some time-related validity logic in Rails.

I read that in Rails 4.1ActiveSupport::Testing::TimeHelpers was added to make it easier for everyone to withstand the test of time. Err, I mean to test time. No disrespect to TimeCop, I know it has its own advantages, but the built-in time helpers for Rails was just enough for my needs.

[pastacode lang=”ruby” message=”” highlight=”” provider=”manual”]

require 'rails_helper'
include ActiveSupport::Testing::TimeHelpers

describe TimeTravel do
  it 'allows person to answer after 1 day' do
    expect(person_can_answer).to be_falsey
    # About to go to the future
    travel(1.day) do
      # While in the future
      expect(person_can_answer).to be_truthy
    # Back to reality
    expect(person_can_answer).to be_falsey


The travel method accepts the time/date difference from Time.now. For example, you want to go to next week, you can travel(1.week) and boom! You’re there.

Meanwhile, travel_to accepts stubbed Time or Date. For example, travel_to Time.new(2004, 9, 20) and voila! You’re back to my 16th birthday.

If travel and travel_to are used without a block, travel_back is needed to go back to the “real” time. Otherwise, it will go back to its original state on its own at the end of the block.

So there. That’s basically how to time travel using ActiveSupport TimeHelpers.

2 comments for “How To Time Travel Using ActiveSupport TimeHelpers

Leave a Reply

Your email address will not be published. Required fields are marked *