0

I am trying to assert that an array of objects contains an expected object. However even though the array indeed contains the expected object (at least from my eyes they do), the spec test kept failing and said the array does not include the object.

Here's the test:

bubble_dtos = [...]
expected_bubble = ...
expect(bubble_dtos).to include(expected_bubble)

And here's the test result:

Failure/Error: expect(bubble_dtos).to include(expected_bubble)
expected [<Soda::DTO::Bubble container_id=594, bubble_type="co2", flavor_id=3515, bubble_sid="soda::bubble:dbid/1413", id=1413, desc="desc1">, <Soda::DTO::Bubble container_id=594, bubble_type="co2", flavor_id=3519, bubble_sid="soda::bubble:dbid/1414", id=1414, desc="desc2">, <Soda::DTO::Bubble container_id=594, bubble_type="co2", flavor_id=3528, bubble_sid="soda::bubble:dbid/1421", id=1421, desc="desc3">] to include <Soda::DTO::Bubble container_id=594, bubble_type="co2", flavor_id=3528, bubble_sid="soda::bubble:dbid/1421", id=1421, desc="desc3">

Does array .include? only check object reference and not object content?

2
  • 1
    I couldn't find anything in the docs, but it looks that it checks only object reference. How do you feel about using include(an_object_having_attributes(...))? Commented Sep 11, 2021 at 14:23
  • 4
    If you want to compare 2 different object with the same content, I think you can implement the equality in the object: rubyguides.com/2017/03/ruby-equality Commented Sep 11, 2021 at 14:54

1 Answer 1

1

Per the ruby 2.7 docs:

include?(object) → true or false

Returns true if the given object is present in self (that is, if any element == object), otherwise returns false.

If your DTO doesn't implement the equality operator == then it will use Object#== which only compares the object reference.

To add the operator to your class:

def ==(object)
  # handle different type
  return false unless object.is_a?(Soda::DTO::Bubble)

  # compare internal variables etc.
  object.container_id == self.container_id
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.