Codium
Codium

Reputation: 3240

Unit testing and DateTime behaviour explanation needed

unit test:

  test "job update date" do
    @job.save
    @job.company = 'New Company'
    now = DateTime.now
    @job.save
    assert_equal @job.updated_at, now
  end

I end up with:

  1) Failure: test_job_update_date(JobTest) [test/unit/job_test.rb:32]: 
  <Mon, 26 Mar 2012 10:36:11 UTC +00:00> expected but was <Mon, 26 Mar 2012 12:36:11   +0200>.

save method from model:

  def save
    if self.created_at.nil?
      self.created_at = DateTime.now
      self.expires_at = self.created_at + Jobeet::Application::ACTIVE_DAYS
    else
      self.updated_at = DateTime.now
    end
    super
  end

Could somebody exaplain me why this happen?

Upvotes: 0

Views: 163

Answers (1)

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

All DateTimes are stored in the database in UTC format, as opposed to your local time.

Rails provides many methods for converting to and from UTC. In your case, you could make your test pass by using the utc method (although I would caution against writing tests which depend on specific Times as you'll surely run into inconsistencies):

assert_equal @job.updated_now, now.utc

Resources:

http://api.rubyonrails.org/classes/DateTime.html

Upvotes: 1

Related Questions