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?
CodePudding user response:
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