Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

ruby - Rspec: "array.should == another_array" but without concern for order

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:

expect(array.to_set).to eq another_array.to_set

or

array.to_set.should == another_array.to_set

This fails when the arrays contain duplicate items.

#sort

For example:

expect(array.sort).to eq another_array.sort

or

array.sort.should == another_array.sort

This fails when the arrays elements don't implement #<=>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try array.should =~ another_array

The best documentation on this I can find is the code itself, which is here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...