LiK*_*KaZ 7 rspec ruby-on-rails rspec-rails ruby-on-rails-5
我尝试测试两个数组数组是否包含相同的元素,而不测试元素的顺序。(Rails 5.2 / Rspec-rails 3.8.2)
例子:
[['a1', 'a2'], ['b1', 'b2']]
[['b2', 'b1'], ['a2', 'a1']]
Run Code Online (Sandbox Code Playgroud)
我尝试使用 match_array 和 contains_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
Run Code Online (Sandbox Code Playgroud)
有匹配器可以做到这一点吗?或者也许是使用可组合匹配器的简单方法?谢谢
编辑我找到的解决方案是:
expect(tab1).to contain_exactly(contain_exactly('a1', 'a2'),
contain_exactly('b1', 'b2'))
Run Code Online (Sandbox Code Playgroud)
但我想找到这样的东西
expect(tab1).to ....... tab2
Run Code Online (Sandbox Code Playgroud)
这里的其他答案是不准确的。您应该根据情况使用contain_exactly或匹配器。match_array请参阅https://rspec.info/documentation/3.12/rspec-expectations/
有两种简单的方法可以实现
describe 'two array with random order' do
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.map(&:sort).sort).to match_array tab3.map(&:sort).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.map(&:sort)).to include *tab3.map(&:sort)
expect(tab1).not_to include *tab4
end
end
Run Code Online (Sandbox Code Playgroud)
我想我找到了解决方案。如果您认为它并不总是有效,请发表评论。
it 'checks that arrays contain the same elements (do not check order)' do
tab1 = [['a1', 'a2'], ['b1', 'b2']]
tab4 = [['b2', 'b1'], ['a2', 'a1']]
expect(tab1.map(&:sort)).to match_array(tab4.map(&:sort))
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10373 次 |
| 最近记录: |