31

我正在尝试测试一个数组是否包含另一个(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”吗?

4

2 回答 2

59

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

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(*test_arr) }
end
于 2013-01-08T12:09:44.223 回答
6

如果你想断言子集数组的顺序,你需要做更多的事情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
于 2014-06-29T18:37:10.823 回答