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.

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.

6 comments for “How To Time Travel Using ActiveSupport TimeHelpers

  1. Brian
    August 27, 2015 at 12:47 pm

    This is great, didn’t even know this library existed, I have always reached for TimeCop when needed

  2. December 13, 2020 at 6:17 pm

    Do you have a spam problem on this blog; I also am a blogger, and I was wanting to know your situation; we have developed some nice practices and we are looking to trade strategies with others, be sure to shoot me an email if interested.|

  3. February 18, 2021 at 12:48 pm

    Howdy! I just want to offer you a huge thumbs up for the excellent info you have right here on this post. I will be returning to your website for more soon.|

  4. February 18, 2021 at 4:38 pm

    When some one searches for his vital thing, thus he/she wants to be available that in detail, thus that thing is maintained over here.|

  5. March 7, 2021 at 2:23 pm

    Hello There. I found your blog using msn. This is a really well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly comeback.|

Leave a Reply

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