Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec equal method

Tags:

From what I have understood, the equal method checks if the object is the same.

person = Person.create!(:name => "David")
Person.find_by_name("David").should equal(person)

This should be true.

But aren't there two different objects here?

How could two objects be the same? I don't understand that.

like image 507
never_had_a_name Avatar asked Aug 08 '10 21:08

never_had_a_name


1 Answers

Rails and RSpec equality tests have a variety of choices.

Rails 3.2 ActiveRecord::Base uses the == equality matcher.

It returns true two different ways:

  • If self is the same exact object as the comparison object
  • If self is the same type as the comparison object and has the same ID

Note that ActiveRecord::Base has the == method which is aliased as eql?. This is different than typical Ruby objects, which define == and eql? differently.

RSpec 2.0 has these equality matchers in rspec-expectations:

a.should equal(b) # passes if a.equal?(b)
a.should eql(b) # passes if a.eql?(b)
a.should == b # passes if a == b

RSpec also has two equality matchers intended to have more of a DSL feel to them:

a.should be(b) # passes if a.equal?(b)
a.should eq(b) # passes if a == b

In your example you're creating a record then finding it.

So you have two choices for testing #find_by_name:

  • To test if it retrieves the exact same object OR an equivalent Person record with the same ID, then use should == or its equivalent a.should eql or its DSL version should eq

  • To test if it uses the exact same object NOT an equivalent Person record with the same ID, then use should equal or its DSL version should be

like image 148
joelparkerhenderson Avatar answered Sep 17 '22 16:09

joelparkerhenderson