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

Biography

Previous
Open Web Foundation Agreement for Activity Streams Signed
Open Web Foundation Agreement for Activity Streams Signed

At Cloud Foundry we care about making life easier for web developers and API developers. Open source helps ...

Next
git config rerere.enabled true
git config rerere.enabled true

There have been times where I performed a rebase and had to resolve conflicts as part of the rebase, and th...