Testing time specific events in RubyOnRails
or It's high time for DRY Time
Testing support in Rails is great. But testing time specific events is still tricky. Certainly, you can put time relative data in your fixtures like this ...
The trouble is that this would be repeated all over the place. A violation of the DRY principle and therefore the fixtures become WET. And it's ugly looking code.
Instead I would like to fix a moment in time that is current and build the test data around it. We start by insisting that only one place in the application creates a new Time object.
Any other code that needs to know the current time will call MyTime.now instead of Time.now
(By the way, this comes in very handy if you need to support muliple timezones, since the decision to use local or utc time can be made here too.)
To fix the time in our test environment create a file called mocks/test/my_time.rb and set whatever time you would like.
Now when the tests run they will always get the same time from MyTime.now and the test data can be built around that.
Created at: Thu Feb 23 01:27:00 +0000 2006 Updated at: Wed Jan 16 12:16:12 +0000 2008

