Rspec:“array.should == another_array”但不关心订单

时间:2010-06-05 02:50:00

标签: ruby testing rspec

我经常想要比较数组并确保它们以任何顺序包含相同的元素。在RSpec中有一种简洁的方法吗?

以下是不可接受的方法:

#to_set

例如:

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

array.to_set.should == another_array.to_set

当数组包含重复项时,此操作失败。

#sort

例如:

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

array.sort.should == another_array.sort

当数组元素未实现#<=>

时,此操作失败

6 个答案:

答案 0 :(得分:261)

尝试array.should =~ another_array

我能找到的最好的文档就是代码本身,here

答案 1 :(得分:226)

自RSpec 2.11起,您还可以使用match_array

array.should match_array(another_array)

在某些情况下,这可能更具可读性。

[1, 2, 3].should =~ [2, 3, 1]
# vs
[1, 2, 3].should match_array([2, 3, 1])

答案 2 :(得分:130)

我发现=~不可预测,并且没有明显原因失败。过去2.14,您应该使用

expect([1, 2, 3]).to match_array([2, 3, 1])

答案 3 :(得分:7)

使用match_array(将另一个数组作为参数),或使用contain_exactly(将每个元素作为单独的参数),有时对于提高可读性很有用。 (docs

示例:

expect([1, 2, 3]).to match_array [3, 2, 1]

expect([1, 2, 3]).to contain_exactly 3, 2, 1

答案 4 :(得分:0)

没有记录得很好,但我还是添加了链接:

Rspec3 docs

expect(actual).to eq(expected)


Rspec2 docs

expect([1, 2, 3]).to match_array([2, 3, 1])

答案 5 :(得分:0)

对于RSpec 3,请使用contain_exactly

有关详细信息,请参见https://relishapp.com/rspec/rspec-expectations/v/3-2/docs/built-in-matchers/contain-exactly-matcher,但这是摘录:

  

contain_exactly匹配器提供了一种以某种方式相互测试阵列的方法   忽略了实际数组和预期数组之间顺序的差异。   例如:

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

正如其他人指出的那样,如果要断言相反的话,则数组应同时匹配内容和顺序,然后使用eq,即:

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