Rspec: "array.should == another
I often want to compare arrays and make sure that they contain the same elements, in any order. Is there a concise way to do this in RSpec?
Here are methods that aren't acceptable:
#to_set
For example:
array.to_set.should == another_array.to_set
This fails when the arrays contain duplicate items.
#sort
For example:
array.sort.should == another_array.sort
This fails when the arrays elements don't implement #<=>
Try array.should =~ another_array
The best documentation on this I can find is the code itself, which is here.
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])
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])
链接地址: http://www.djcxy.com/p/59296.html
上一篇: 我如何在Rspec中只运行特定的测试?