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:
- 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:
def setup
pretend_now_is(Time.local(2007, 8, 1)) # position *all* tests back in time!
end
def teardown
Time.reset # jump back to the present
end
or just do some time travel for a code block:
(These code samples come from here. Thank you!)
def test_decades
pretend_now_is(Time.local(1960)) do
assert_equal(1960, Time.now.year)
end
pretend_now_is(Time.local(1970)) do
assert_equal(1970, Time.now.year)
end
# ...
end - 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:
Thank you!