Rspec: "array.should == another_array" but without concern for order
Use match_array
, which takes another array as an argument, or contain_exactly
, which takes each element as a separate argument, and is sometimes useful for readability. (docs)
Examples:
expect([1, 2, 3]).to match_array [3, 2, 1]
or
expect([1, 2, 3]).to contain_exactly 3, 2, 1
I've found =~
to be unpredictable and it has failed for no apparent reason. Past 2.14, you should probably use
expect([1, 2, 3]).to match_array([2, 3, 1])
Since RSpec 2.11 you can also use match_array
.
array.should match_array(another_array)
Which could be more readable in some cases.
[1, 2, 3].should =~ [2, 3, 1]
# vs
[1, 2, 3].should match_array([2, 3, 1])
Try array.should =~ another_array
The best documentation on this I can find is the code itself, which is here.