0

I have the following Rspec test:

it 'creates an initial version with all the versionable attributes' do
  resource = create(:versionable_resource)
  version_attributes = resource.initial_version.new_attributes.sort
  expect(version_attributes).to eq(resource.versionable_attributes.sort)
end

Both version_attributes and resource.versionable_attributes are hashes. They have the exact same contents. However, the eq statement is failing with:

   expected: [["r_boolean", true], ["r_date", Sun, 26 Jan 2014], ["r_datetime", Sun, 26 Jan 2014 23:00:56 UTC +00:00], ["r_float", 3.14], ["r_integer", 3], ["r_string", "my string"], ["r_text", "my text"], ["r_time", 2014-01-26 17:00:56 -0600]]
        got: [["r_boolean", true], ["r_date", Sun, 26 Jan 2014], ["r_datetime", Sun, 26 Jan 2014 23:00:56 UTC +00:00], ["r_float", 3.14], ["r_integer", 3], ["r_string", "my string"], ["r_text", "my text"], ["r_time", 2014-01-26 17:00:56 -0600]]

   (compared using ==)

As you can see, the contents are identical. Why is this failing? Should I use a different matcher than eq? I've tried eql and equal as well, and all fail the same way.

nullnullnull
  • 8,039
  • 12
  • 55
  • 107

1 Answers1

2

You don't say what the various methods do (e.g. initial_version, versionable_attributes, etc.), but if either the expected or the actual value of your comparison is from your database and the other isn't, the difference is likely due to the database maintaining less precision than Ruby itself, as explained in Trouble comparing time with RSpec

Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
  • Unfortunately, it looks like you're right. When I remove times and datetimes from the comparison, it works as expected. Do you happen to know if you can remove nanoseconds from a Ruby time object? – nullnullnull Jan 26 '14 at 23:36
  • I don't know how to remove the nanoseconds from a Ruby time object, but you can create a new object with 0 nanoseconds by calling `change(nsec: 0)` on it. – Peter Alfvin Jan 27 '14 at 00:14