Rspec: “array.should == another_array” but without concern for order

前端 未结 6 2051

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 are

6条回答
  •  没有蜡笔的小新
    2020-12-12 10:31

    For RSpec 3 use contain_exactly:

    See https://relishapp.com/rspec/rspec-expectations/v/3-2/docs/built-in-matchers/contain-exactly-matcher for details, but here's an extract:

    The contain_exactly matcher provides a way to test arrays against each other in a way that disregards differences in the ordering between the actual and expected array. For example:

        expect([1, 2, 3]).to    contain_exactly(2, 3, 1) # pass
        expect([:a, :c, :b]).to contain_exactly(:a, :c ) # fail
    

    As others have pointed out, if you want to assert the opposite, that the arrays should match both contents and order, then use eq, ie.:

        expect([1, 2, 3]).to    eq([1, 2, 3]) # pass
        expect([1, 2, 3]).to    eq([2, 3, 1]) # fail
    

提交回复
热议问题