Is there a good way in Rspec to compare two ActiveRecord objects while ignoring id, &c? For example, say I'm parsing one object from XML and loading the other from a fixture, and what I'm testing is that my XML parser works correctly. What I currently have is a custom matcher with
actual.attributes.reject{|key,v| %w"id updated_at created_at".include? key } == expected.attributes.reject{|key,v| %w"id updated_at created_at".include? key }
But I'm wondering if there's a better way.
And then slightly more complicated, but is there a way to do a similar thing on a set? Say said XML parser also creates several objects that belong_to the original object. So the set I'm ending up with should be identical except for id, created_at, &c, and I'm wondering if there's a good way to test that beyond just cycling through, clearing out those variables, and checking.
A shorter way to write the above would be actual.attributes.except(:id, :updated_at, :created_at)
.
If you are using this a lot, you can always define your own matcher like this:
RSpec::Matchers.define :have_same_attributes_as do |expected|
match do |actual|
ignored = [:id, :updated_at, :created_at]
actual.attributes.except(*ignored) == expected.attributes.except(*ignored)
end
end
Put this into your spec_helper.rb
you can now say in any example:
User.first.should have_same_attributes_as(User.last)
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With