Can we go anywhere we want at any time?
You can do anything you want.
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:
- Copy the above code to a file and save it as test/time_helper.rb
- Require it in your test:
require File.dirname(__FILE__) + '/../time_helper'
- Either set the time for all the tests in the file:
pretend_now_is(Time.local(2007, 8, 1)) # position *all* tests back in time!
Time.reset # jump back to the present
or just do some time travel for a code block:
(These code samples come from here. Thank you!)
- Find a street where your De Lorean can reach 88 mph and run your time traveling tests!
If this was useful for you, please take a minute and recommend me: