我尝试测试两个数组是否包含相同的元素,而不测试元素的顺序。(Rails 5.2 / Rspec-rails 3.8.2)
示例:
[['a1', 'a2'], ['b1', 'b2']]
[['b2', 'b1'], ['a2', 'a1']]
我尝试过使用match_array和contain_exactly,但这仅适用于数组的第一级。
tab1 = [['a1', 'a2'], ['b1', 'b2']]
tab2 = [['b1', 'b2'], ['a1', 'a2']]
tab3 = [['a2', 'a1'], ['b2', 'b1']]
tab4 = [['b2', 'b1'], ['a2', 'a1']]
expect(tab1).to match_array tab2 # true
expect(tab1).to match_array tab3 # false
expect(tab1).to match_array tab4 # false
是否有匹配器可以做到这一点?还是使用可组合匹配器的简单方法?谢谢
编辑我找到的解决方案是:
expect(tab1).to contain_exactly(contain_exactly('a1', 'a2'),
contain_exactly('b1', 'b2'))
但是我想找到类似的东西
expect(tab1).to ....... tab2
没有内置的匹配器,但是您可以编写一个。
那表示您可能只需将两侧弄平:
tab1 = [['a1', 'a2'], ['b1', 'b2']]
tab2 = [['b1', 'b2'], ['a1', 'a2']]
tab3 = [['a2', 'a1'], ['b2', 'b1']]
tab4 = [['b2', 'b1'], ['a2', 'a1']]
it { expect(tab1.flatten).to match_array tab2.flatten } # true
it { expect(tab1.flatten).to match_array tab3.flatten } # true
it { expect(tab1.flatten).to match_array tab4.flatten } # true
而且:
tab5 = [['b2'], ['b1', 'a2', 'a1']]
tab6 = [['b2', 'b1', 'a2'], ['a1']]
it { expect(tab5.flatten).to match_array tab6.flatten } # also true
可能不是您想要的。
有两种简单的方法来描述'具有随机顺序的两个数组'做
it 'arrays are equals if content is same' do
tab1 = [['a1', 'a2'], ['b1', 'b2']]
tab2 = [['b1', 'b2'], ['a1', 'a2']]
tab3 = [['a2', 'a1'], ['b2', 'b1']]
tab4 = [['b2', 'b1'], ['a2', 'a1']]
#option 1
expect(tab1.sort).to match_array tab2.sort
expect(tab1.sort).not_to match_array tab3.sort
expect(tab1.sort).not_to match_array tab4.sort
# Option 2
expect(tab1).to include *tab2
expect(tab1).not_to include *tab3
expect(tab1).not_to include *tab4
end
end