Rspec Equal Method

Rspec equal method

equal checks if the reference is the same. It corresponds to the Object#equal? method. You want to use == to compare these objects.

RSpec - equality match, two different instances

With all the given informations eq can't work out of the box. You have multiple options:

  • compare every attribute like expect(sample_row.service).to eq(parse('/file_test.csv').first.service)
  • implement Comparable
  • use a third party gem like equalizer to define equality
  • add a method to Call that converts all attributes to a hash and compare those Hashes
  • create your own Matcher
  • ...

Rspec `eq` vs `eql` in `expect` tests

There are subtle differences here, based on the type of equality being used in the comparison.

From the Rpsec docs:

Ruby exposes several different methods for handling equality:

a.equal?(b) # object identity - a and b refer to the same object
a.eql?(b) # object equivalence - a and b have the same value
a == b # object equivalence - a and b have the same value with type conversions]

eq uses the == operator for comparison, and eql ignores type conversions.

How to use `or` in RSpec equality matchers (Rails)

How about this:

expect(body['classification'].in?(['Apt', 'Hourse']).to be_truthy

Or

expect(body['classification']).to eq('Apt').or eq('Hourse')

Or even this:

expect(body['classification']).to satify { |v| v.in?(['Apt', 'Hourse']) }

Compare values without regard to address using RSpec

I see two main ways of doing what you want.

You can either implement a custom matcher or override the == method on the Person class. Second is nice, because you can then use the equality in other places, even outside of tests. First method is good if what you are comparing is very specific (e.g. you don't care for all person's attributes in a particular test).

RSpec: How to compare have_received arguments by object identity?

This happens because Comparable implements ==, so your objects are treated as being equal in regards to ==:

b1 = B.new(0)
b2 = B.new(0)

b1 == b2 #=> true

To set a constraint based on object identity, you can use the equal matcher: (or its aliases an_object_equal_to / equal_to)

expect(s).to have_received(:call).with(an_object_equal_to(b1)).once

Under the hood, this matcher calls equal?:

b1 = B.new(0)
b2 = B.new(0)

b1.equal?(b2) #=> false


Related Topics



Leave a reply



Submit