Testing Arrays In RSpec

Three patterns for testing ruby arrays in RSpec, pick the one most appropriate for your use case

Today we’re going to talk about testing Arrays in RSpec and share three common patterns you will end up using in your testing.

Lets start with the definition of what an array is, because it helps inform some of our testing choices.

Arrays are ordered, integer-indexed collections of any object.

https://ruby-doc.org/core-2.7.0/Array.html

The important thing here is “ordered”. With unordered collections, (1, 2, 3) is identical to (3, 2, 1). With an ordered list, like an array, [1, 2, 3] is not the same as [3, 2, 1].

When You Don’t Care About Order And Know The Array

The first pattern is when you know the array you’re expecting to come back, but you don’t care about the order.

In this case we would use match_array.

it 'matches our array, without caring about order' do
  my_array = [1, 2, 3]
  expect([3, 2, 1]).to match_array(my_array)
end

When You Don’t Care About Order And Don’t Know The Array

The next pattern is when you don’t know the array you’re expecting to come back, but know the elements that will come back, and you don’t care about the order.

In this case we would use contain_exactly.

it 'matches our elements, without caring about order' do
  expect([3, 2, 1]).to contain_exactly(1, 2, 3)
end

When You Care About Order

One of the reasons we would not care about order, even though we know that arrays are ordered, is that we’re making a conscious call that “my code doesn’t care about order” and when that is the case if our tests care about order then we’re introducing unneccessary brittleness. If our array order changes for some reason our test would fail, even though it wouldn’t impact our system.

Our final pattern is when our code actually cares about order.

In this case we can use the humble eq.

it 'matches our array, caring about order' do
  expect([1, 2, 3]).to eq([1, 2, 3)
end

Recent posts View all

CSS

Firefox Printing Issue for Grid CSS

If your body using a layout of grid is causing issues when printing, here is a fix

Productivity

The two snippets that cover 90% of my LinkedIn messages

These are the two snippets of text that can end up answering 90% of my messages on LinkedIn