Rspec: Check if array includes object which includes property

Viewed 24159

I have a json array full of objects.

my_array = [{id => 6, name => "bob"}, 
           {id => 5, name => "jim"}, 
           {id => 2, name => "steve"}]

I need to see if the array holds an object which contains an attribute "id" that is set to 5. The "name" attribute is unknown.

How do I do this in rspec?

I know if I had the name attribute I know I could just do:

my_array.should include({:id => 5, :name => "jim"}) 
7 Answers

It is also possible using the having_attributes alias:

expect(my_array).to include( an_object_having_attributes(id: 5) )

or, as in my own use case, matching the whole array:

expect(my_array).to contain_exactly(
  an_object_having_attributes(id: 5),
  an_object_having_attributes(id: 6),
  an_object_having_attributes(id: 2)
)
Related