Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails assert_equal doesn't always work with DateTimes

I get an error in my functional test when using assert_equal:

  1) [31mFailure[0m:
test_should_allow_dealer_to_extend_offer:21
<Thu, 14 Apr 2011 23:59:59 PDT -07:00> expected but was
<Thu, 14 Apr 2011 23:59:59 PDT -07:00>.

Notice that the two show the same time and time zone. I checked and they are the same class type (ActiveSupport::TimeWithZone). So why aren't they equal?

It's a standard DateTime field in the database, which I think is only stored down to the second right?

I can get it to pass by converting them to integers or using assert_in_delta with a range of 1 minute. But was just wondering.

Btw this is Rails 2.3.8 and MySQL.

like image 994
Brian Armstrong Avatar asked Apr 05 '11 18:04

Brian Armstrong


1 Answers

I'm getting the same error too. It looks like this was reported back in 2009:

I've seen this happen in tests before - typically caused by the database having a different time resolution than the system. So even though the two times print identically, one is really (for instance) 15:45:32.012445362 and the DB loads back 15:45:32, which doesn't compare as equal.

The suggested solution, which worked for me:

In your tests, you can try coercing to_a before comparing; usec value isn't returned in the to_a representation:

like image 90
Craig Walker Avatar answered Nov 09 '22 05:11

Craig Walker