Home > Back-end >  Rspec test expecting memory values to be the same?
Rspec test expecting memory values to be the same?

Time:07-06

I have this Rspec test that is failing and i'm not understanding how to solve it.

it seems like the error is because they are differents instances of the object, so they got differents memory values.

How can i maintain a memory value object when create a object that will behaviour in the same way if given the same input?

describe '#==' do
let(:cpf) {described_class.new('01201201202')}

it 'verifies the key equality' do
    expect(cpf).to eq described_class.new('01201201202')

Error:

 1) PixKey#== verifies the key equality
 Failure/Error: expect(cpf).to eq described_class.new('01201201202')

   expected: #<PixKey:0x0000018d191b8670 @value="01201201202", @key="01201201202", @type="cpf">
        got: #<PixKey:0x0000018d191b8b70 @value="01201201202", @key="01201201202", @type="cpf">

   (compared using ==)

   Diff:
   @@ -1,4  1,4 @@
   -#<PixKey:0x0000018d191b8670
    #<PixKey:0x0000018d191b8b70
     @key="01201201202",
     @type="cpf",
     @value="01201201202">

Any ideas would be great.

CodePudding user response:

The default behavior of the == method returns true when both objects refer to the same hash key. Because in your example both elements are different instances their hash value would be different.

If you want two instances of PixKey to be considered equal if they have the same @value and/or @key then you need to override the default implementation with your own implementation, for example like this:

# in your `PixKey` class
def ==(other)
  self.class == other.class && @key == other.key && @value == other.value
end
  • Related