Array Matchers in RSpec

Bailey Baker
Beam Benefits

--

In RSpec testing, there are numerous matchers used to define expectations of a test. Luckily, these matchers read like plain sentences in English which makes it even easier to understand the purpose of a test.

When testing in RSpec, you will probably need to test an array at some point. There are 3 common methods when testing arrays. The methods are contain_exactly, match_array, and eq.

The first method, contain_exactly, allows you to test arrays against each other. It can be used when you don’t know the order of the array you’re expecting to come back but know the elements the array will contain. Here is an example of a passing test using contain_exactly.

it ‘matches our elements, without caring about order’ do  expect([4, 5, 6]).to contain_exactly(6, 5, 4)end

However, the following test will fail because not all of the elements are included.

it ‘matches our elements, without caring about order’ do  expect([4, 5, 6]).to contain_exactly(6, 4)end

The match_array method can also be used to test arrays against each other when you don’t know the order of the array but you know the elements it contains. You may be thinking to yourself that match_array sounds exactly like contain_exactly. It turns out, match_array and contain_exactly are very similar in that order does not matter for both. The only difference is that the match_array method requires the expected array to be given as a single array argument rather than as individual elements.

it ‘matches the array, without caring about order’ do  the_array = [7, 8, 9]  expect([9, 7, 8]).to match_array(the_array)end

If you test two arrays against each other that do not match exactly, this will still fail just like when using contain_exactly. Here is an example:

it ‘matches the array, without caring about order’ do  the_array = [7, 8, 9]  expect([9, 7]).to match_array(the_array)end

The last method is eq. The eq method can be used when you do care about the order of the array and this will check for equality between a subject and its expectation.

it ‘matches our array, and cares about order’ do  expect([10, 11, 12]).to eq([10, 11, 12])end

As you can expect, testing two arrays against each other that contain the same elements but are different in order will result in a failing test. Here is an example:

it ‘matches our array, and cares about order’ do  expect([12, 10, 11]).to eq([10, 11, 12])end

That was a quick overview of a couple of the popular array method matchers in RSpec. There’s no best way to assert expectations against arrays but knowing the different options available and how they work can lead to easier testing and more accurate assertions.

--

--