Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created July 18, 2011 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreyiacono/1088550 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/1088550 to your computer and use it in GitHub Desktop.
Test sequence discovering how microseconds can cause your tests to fail while reporting that all looks equal
# Givens: Rails 3.0.7, Ruby 1.9.2, with RSpec2 (2.6.4) and FactoryGirl (1.3.3)
# original test ...
require 'spec_helper'
describe Item do
context 'a trivial example' do
before do
@item = Factory.create(:item)
end
it 'updates created_at without issue' do
new_time = 1.day.ago
@item.created_at = new_time
@item.created_at.should == new_time
end
end
end
# This fails with the perplexing error of ...
# Failure/Error: @item.created_at.should == new_time
# expected: Sat, 16 Jul 2011 23:14:08 UTC +00:00
# got: Sat, 16 Jul 2011 23:14:08 UTC +00:00 (using ==)
# "WTF?" I thought, "Those are the same!"
# Next, I checked if #to_s'ing each did anything
require 'spec_helper'
describe Item do
context 'a trivial example' do
before do
@item = Factory.create(:item)
end
it 'updates created_at without issue' do
new_time = 1.day.ago
@item.created_at = new_time
@item.created_at.to_s.should == new_time.to_s
end
end
end
# This passes. I next started to look into what types of objects were being returned.
# Both were ActiveSupport::TimeWithZone, dead end.
# Next, I tried #to_date'ing each, which got a passing test. #to_datetime'ing each caused a failure.
# So it is something with the time component.
# After a little digging, I thought to check microseconds:
require 'spec_helper'
describe Item do
context 'a trivial example' do
before do
@item = Factory.create(:item)
end
it 'TEMP: helps me examine the two dates' do
new_time = 1.day.ago
@item.created_at = new_time
@item.created_at.usec.should == new_time.usec
end
end
end
# Fail! Yay! Full error reported by RSpec is:
# Failure/Error: @disease_state.created_at.usec.should == new_time.usec
# expected: 432826
# got: 0 (using ==)
# So the microseconds part is being populated when using 1.day.ago
# Solution? Get rid of the microseconds!
require 'spec_helper'
describe Item do
context 'a trivial example' do
before do
@item = Factory.create(:item)
end
it 'updates created_at without issue' do
new_time = Time.zone.local(2011, 7, 16, 12, 0, 0)
@item.created_at = new_time
@item.created_at.should == new_time
end
end
end
# All green. Don't let the microseconds issue bite you in the ass in your test assertions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment