ruby RSpec:我如何在期望语法中使用数组包含匹配器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14890375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:45:09  来源:igfitidea点击:

RSpec: How could I use the array include matcher in the expect syntax

rubyunit-testingrspec

提问by mrzasa

I use new rspec syntax(expectinstead of should) and I'd like to test if an array includes elements of another array. In the old syntax it would be:

我使用新的 rspec 语法expect而不是should),我想测试一个数组是否包含另一个数组的元素。在旧语法中,它将是:

array1.should include(array2)

In the new syntax I tried to write:

在我尝试编写的新语法中:

expect(array1).to include(array2)

but I got an error (that's quite reasonable):

但我得到了一个错误(这是非常合理的):

TypeError: wrong argument type Array (expected Module)

Then I wrote:

然后我写道:

expect(array1).to be_include(array2)

but it's ugly ;-) UPDATE:and it didn't work: apparently it cheks if array2 is element of array1 not if all elements of array2 are included in array1.

但它很丑;-) 更新:它没有用:显然它检查 array2 是否是 array1 的元素,而不是 array2 的所有元素都包含在 array1 中。

Finally I wrote:

最后我写道:

expect(array1 & array2).to eq(array2)

but it's not the prettiest solution. Do you know any better?

但这不是最漂亮的解决方案。你知道更好吗?

回答by Myron Marston

You need to splat the arguments when passing them to the array matcher:

将参数传递给数组匹配器时,您需要将它们分开:

expect(array1).to include(*array2)

This is because you usually list out literals, e.g.:

这是因为您通常会列出文字,例如:

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

That said, expect(array1).to include(array2)should not fail with a weird error like you got, and in fact it works and passes in an example like:

也就是说,expect(array1).to include(array2)不应该因为你得到的奇怪错误而失败,事实上它可以工作并通过一个例子:

  it 'includes a sub array' do
    array2 = ["a"]
    array1 = [array2]
    expect(array1).to include(array2)
  end

回答by William Hu

Try this one:

试试这个:

expect(array1).to include *array2

回答by Oto Brglez

To test if one array is subset of another array its perhapse good idea to introduce set. And then you can write it like this... (Solution uses Set#subset?)

要测试一个数组是否是另一个数组的子集,引入set 可能是个好主意。然后你可以这样写......(解决方案使用Set#subset?

require "set"

describe "Small test" do
  let(:array1) { %w{a b c d} }
  let(:array2) { %w{b c} }

  let(:array1_as_set) { array1.to_set }
  let(:array2_as_set) { array2.to_set }

  subject { array2_as_set }

  context "inclusion of w/ \"expect\"" do
    it { expect(subject).to be_subset(array1_as_set) }
  end

  context "inclusion of w/ \"should\"" do
    it { should be_subset(array1_as_set) }
  end

end