Ruby / Rspec: Can I compare the contents of two objects?

I created two different objects in a ruby ​​with exactly the same attributes and values.

Now I would like to compare that the contents of both objects are the same, but the following comparisons:

actual.should == expected actual.should eq(expected) actual.should (be expected) 

failure:

  Diff: @@ -1,4 +1,4 @@ -#<Station:0x2807628 +#<Station:0x2807610 

Is there any way in rspec / ruby ​​to easily achieve this?

Hooray!!

+8
ruby rspec
source share
4 answers

The idiomatic way to do this is to override the #== operator:

 class Station def ==(o) primary_key == o.primary_key end def hash primary_key.hash end end 

When you do this, you usually want to override the #hash method. Less common override of #eql? or #equal? .

EDIT . Another thing you can do in this particular case, which does not include overriding #== , is to create a custom RSpec mapping .

+9
source share

A little late, but you can serialize it, for example:

 require 'json' expect(actual.to_json).to eq(expected.to_json) #new rspec syntax actual.to_json.should eq(expected.to_json) #old rspec syntax 
+2
source share

Perhaps you should consider overloading an equal operator on an object.

0
source share

Use the has_attributes attribute to indicate that the attributes of the object match the expected attributes:

  Person = Struct.new(:name, :age) person = Person.new("Jim", 32) expect(person).to have_attributes(:name => "Jim", :age => 32) expect(person).to have_attributes(:name => a_string_starting_with("J"), :age => (a_value > 30) ) 

RSpec docs for Relishapp

0
source share

All Articles