Rspec 'Eq' VS 'Eql' in 'Expect' Tests

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.

Rspec: using OR in expect .to eq statement

You can or two matchers together:

expect(@note.value).to eq(2).or eq(-2)

For more info see.

RSpec: difference between should == ... and should eql(...)

It's rather simple, really: should == sends the == message to the test subject, should eql sends the eql? message to the test subject. In other words: the two different tests send two completely different messages which invoke two completely different methods and thus do two completely different things. In particular, eql? is stricter than == but less strict than equals?.

Rails Rspec integer equals string (1 == 1)

Instances of different classes cannot be equal.

You need to convert them so they become instances of the same Class :

"1234" == 1234
#=> false
"1234".to_i == 1234
#=> true
1234.to_s == "1234"
#=> true

So in your example :

expect(variable.to_i).to eql model.id
# or less logical :
expect(variable).to eql model.id.to_s

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
  • ...


Related Topics



Leave a reply



Submit