What is the best way to test an array of hashes with RSpec?

advertisements

I'm trying to test array of hashes with RSpec, but I don't know how to test them because the hash order could change. E.G:

[{name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}}, {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}]

is the same as:

[{name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}, {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}}]

What is the best way to test them using RSpec? Should I use a custom matcher?


You could use RSpec's contain_exactly matcher, that doesn't care about ordering.

expect(collection).to contain_exactly(
  {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}},
  {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}
)

Another option is to use match_array, which behaves similarly (order is not important), but the expected argument is an array, rather than individual elements.

expect(collection).to match_array([
  {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}},
  {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}
])