Rails Time Travel: Manipulating Time.now for Tests

Posted on 27 May 2008 by Johannes Fahrenkrug. Tags: Programming Tutorials Ruby rails
Can we go anywhere we want at any time?
You can do anything you want.

Check out the new version about time travel with RSpec!

Do you have code in your Ruby on Rails models that depends on the current date and time? I do. And I want to test it to make sure it works right. In my case a certain date is only valid if it is in the current month or in the previous month but only if it's not the 11th day of the month yet. If today were the 10th of May - for example - a date in April would be valid. If today were the 11th of May, a date in April wouldn't be valid anymore, though.
Just testing this piece of code if the day the tests are being run happens to be below the 11th day of the month is not a solution, of course. So I googled a bit and found this wonderful piece of code.

These are the steps to get your Rails Time Machine (tm) up and running:
  1. Copy the above code to a file and save it as test/time_helper.rb
  2. Require it in your test:
    require File.dirname(__FILE__) + '/../time_helper'
  3. Either set the time for all the tests in the file:

    def setup
    pretend_now_is(Time.local(2007, 8, 1)) # position *all* tests back in time!

    def teardown
    Time.reset # jump back to the present

    or just do some time travel for a code block:

    def test_decades
    pretend_now_is(Time.local(1960)) do
    assert_equal(1960, Time.now.year)
    pretend_now_is(Time.local(1970)) do
    assert_equal(1970, Time.now.year)
    # ...
    (These code samples come from here. Thank you!)
  4. Find a street where your De Lorean can reach 88 mph and run your time traveling tests!
Please give my regards to Bill and Ted if you meet them.

If this was useful for you, please take a minute and recommend me:
Recommend Me
Thank you!


Please keep it clean, everybody. Comments with profanity will be deleted.

blog comments powered by Disqus