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