Rails Time inconsistencies with rspec

Viewed 17157

I'm working with Time in Rails and using the following code to set up the start date and end date of a project:

start_date ||= Time.now
end_date = start_date + goal_months.months

I then clone the object and I'm writing rspec tests to confirm that the attributes match in the copy. The end dates match:

original[end_date]:  2011-08-24 18:24:53 UTC
clone[end_date]:     2011-08-24 18:24:53 UTC

but the spec gives me an error on the start dates:

expected: Wed Aug 24 18:24:53 UTC 2011,
     got: Wed, 24 Aug 2011 18:24:53 UTC +00:00 (using ==)

It's clear the dates are the same, just formatted differently. How is it that they end up getting stored differently in the database, and how do I get them to match? I've tried it with DateTime as well with the same results.

Correction: The end dates don't match either. They print out the same, but rspec errors out on them as well. When I print out the start date and end date, the values come out in different formats:

start date: 2010-08-24T19:00:24+00:00
end date: 2011-08-24 19:00:24 UTC
10 Answers

Adding .to_datetime to both variables will coerce the datetime values to be equivalent and respect timezones and Daylight Saving Time. For just date comparisons, use .to_date.

An example spec with two variables: actual_time.to_datetime.should == expected_time.to_datetime

A better spec with clarity: actual_time.to_datetime.should eq 1.month.from_now.to_datetime

.to_i produces ambiguity regarding it's meaning in the specs.

+1 for using TimeCop gem in specs. Just make sure to test Daylight Saving Time in your specs if your app is affected by DST.

Related