RSpec: Asserting arrays' content without regard to order

May 21, 2012 Mark Rushakoff

Sometimes I want to make assertions about the content of an array when the order of its content is not guaranteed:

nums = [1,2,3].shuffle
nums.length.should == 3
nums.should include 1
nums.should include 2
nums.should include 3

(Of course this is a contrived example, and we could just write nums.sort.should == [1,2,3]. But sometimes we are working with objects that aren’t already sortable.)

I recently found out that RSpec has an array matcher that is specifically intended for this use case, via the =~ operator:

[1,2,3].shuffle.should =~ [1,2,3]

About the Author


More Content by Mark Rushakoff
git add -e
git add -e

git add -e is like git add -p, except instead of adding things at the hunk level, you edit the entire patch...

Introducing Sympatico's New Mobile-Friendly Site!
Introducing Sympatico's New Mobile-Friendly Site!

In today’s world of immediacy and convenience, no one wants to jump around from webpage to webpage for info...

Enter curious. Exit smarter.

Register Now