Thursday 6 December 2007

Rails Gotchas: fixtures created_at when?

So - I updated some date-sensitive fixtures and re-ran all my rake tests... and suddenly everything went funny.

First off the rack: empty created_at date

The first problem seemed to be that the created_at date just didn't get set at all. I even printed it out in my test case with an "inspect" and it was showing: "created_at" => "0000-00-00 00:00:00". Pretty nasty.

I checked the fixture and even printed out the date I was trying to save (Time.now.utc) to make sure that Time was working in the fixtures... to no avail, until I realised I'd accidentally knocked off the .to_s(:db) from the end. I added that back and magickally my fixtures were loading the dates again (yay).

Next up: intermittent wierdness

So then there was an intermittant, but persistent error that was really weird. The method I was testing boils down to me pulling out a set of objects and ordering them by creation-date and checking the value of the last one in line. I was checking that if I created a new one - I actually got the new value out the other end. Now the problem was - sometimes I did... and sometimes I didn't... sometimes I'd run rake-test and it'd work... and I'd run it straight afterward and it'd break again.

Then I remembered that datetimes only have a one-second granularity... and some of my tests probably ran less than one second after setup. So I used 1.second.ago.utc.to_s(:db) in the fixtures and it all went away. :P

3 comments:

Anonymous said...

First off the rack?

And not a pun?

That's -1,000 points in geelf!

Anonymous said...

Thank you so so much.

Absolute legend.

You've just saved my dissertation!!!!!

Taryn East said...

You're very welcome :)