Rspec:“array.should == another_array";但不关心秩序 [英] Rspec: "array.should == another_array" but without concern for order

查看:44
本文介绍了Rspec:“array.should == another_array";但不关心秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想比较数组并确保它们以任何顺序包含相同的元素.在 RSpec 中是否有一种简洁的方法可以做到这一点?

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:

例如:

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

array.to_set.should == another_array.to_set

当数组包含重复项时失败.

This fails when the arrays contain duplicate items.

例如:

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

array.sort.should == another_array.sort

当数组元素没有实现 #<=>

推荐答案

使用 match_array,它将另一个数组作为参数,或者 contain_exactly,它将每个元素作为一个单独的参数,有时对可读性很有用.(文档)

Use match_array, which takes another array as an argument, or contain_exactly, which takes each element as a separate argument, and is sometimes useful for readability. (docs)

示例:

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

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

这篇关于Rspec:“array.should == another_array";但不关心秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆