Yesterday I modified an old app to turn off a feature for records that were more than a certain number of days old. This is an old enough app that the test data is still yaml fixture files, and in the fixtures I see records with attributes like so:
published_at: 2006-08-25 00:00:00 -07:00 created_at: 2006-08-24 00:00:00 -07:00 updated_at: 2006-08-25 00:00:00 -07:00
And of course, the tests code also makes assumptions about absolute dates…
get :show, :year => '2006', :month => '08', :day => '24' assert_not_nil assigns[:article]
That makes adding tests that need to check for dates relative to the current date very difficult to integrate into the test suite. It also means that over time, your fixture data gets “stale” and you don’t have any data that appears to be recent, which may or may not matter to your application.
One way to deal with this is to mock time in your test code, so that tests always run at the same effective time, so the hardwired absolute dates in fixtures are always relatively the same age. I think that’s a good Plan B, but I prefer Plan A.
Plan A is to create your test data with dates and times relative to when the tests are being run. You can do that in yaml fixtures by embedding ruby in the yaml:
published_at: <%= 2.days.ago.to_s(:db) %> created_at: <%= 3.days.ago.to_s(:db) %> updated_at: <%= 2.days.ago.to_s(:db) %>
And in your test code, be flexible too:
pub = article.published_at.to_date get :show, :year => pub.year.to_s, :month => pub.month.to_s, :day => pub.mday.to_s assert_not_nil assigns[:article]
Keep your test dates relative, and a year from now you’ll thank yourself (or somebody else will).
About the Author