【问题标题】:RSpec: How could I use the array include matcher in the expect syntaxRSpec:我如何在期望语法中使用数组包含匹配器
【发布时间】:2013-02-15 07:59:35
【问题描述】:

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

array1.should include(array2)

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

expect(array1).to include(array2)

但我得到了一个错误(这很合理):

TypeError: wrong argument type Array (expected Module)

然后我写道:

expect(array1).to be_include(array2)

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

最后我写了:

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

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

【问题讨论】:

    标签: ruby unit-testing rspec


    【解决方案1】:

    您需要在将参数传递给数组匹配器时将其分解:

    expect(array1).to include(*array2)
    

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

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

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

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

    【讨论】:

    • 如何测试不包含?我试过not_to include,但它引发了一个错误:expect([1, 2, 3]).not_to include(1) raises RSpec::Expectations::ExpectationNotMetError: expected [1, 2, 3] not to include 1
    • @IvánCortésRomero 您的示例失败了,因为1 实际上包含在[1,2,3] 中,但是您告诉 rspec 期望它不会包含。通过:expect([1, 2, 3]).not_to include(4).
    【解决方案2】:

    试试这个:

    expect(array1).to include *array2
    

    【讨论】:

      【解决方案3】:

      要测试一个数组是否是另一个数组的子集,引入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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多