RSpec中如何判断数组包含另一个数组?

37

我正在尝试测试一个数组是否包含另一个数组(rspec 2.11.0)

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(1,3) }
  it { should eval("include(#{test_arr.join(',')})")}
  #failing
  it { should include(test_arr) }
end    

这是结果 rspec spec/test.spec ..F

Failures:

  1) 1 3 7 
     Failure/Error: it { should include(test_arr) }
       expected [1, 3, 7] to include [1, 3]
     # ./spec/test.spec:7:in `block (2 levels) in <top (required)>'

Finished in 0.00125 seconds
3 examples, 1 failure

Failed examples:

rspec ./spec/test.spec:7 # 1 3 7 

include rspec方法现在不再接受数组参数,有没有更好的方法来避免使用"eval"?

2个回答

66

只需使用展开运算符(*),它可以将一个元素数组展开为可传递给方法的参数列表:

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(*test_arr) }
end

4
哇塞!这简直太惊人了……说真的,在规范中这真的非常非常有用,我不知道 #include 支持参数列表。谢谢! - Aldo 'xoen' Giambelluca
我了解了展开运算符,如果数组在一行内定义,则甚至不需要使用它。在我的情况下,我使用了 it { should include(1, 3) }(编辑:这正是展开运算符所做的) - Alex Wally

7
如果你想要确定子集数组的顺序,那么你需要做更多的事情,而不只是使用 "should include(..)",因为 RSpec 的 "include" 匹配器仅断言每个元素是否出现在数组中的任何位置,而不是所有参数按顺序出现。
我最终使用了 "each_cons" 来验证子数组是否按顺序出现,就像这样:
describe [1, 3, 5, 7] do
  it 'includes [3,5] in order' do
    subject.each_cons(2).should include([3,5])
  end

  it 'does not include [3,1]' do
    subject.each_cons(2).should_not include([3,1])
  end
end

老实说这太棒了。让我能够精确查找我需要的东西。 - Asfand Qazi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接