我正在尝试测试一个数组是否包含另一个(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
包含rspec mehod no接受数组参数,这是避免“eval”的更好方法吗?
答案 0 :(得分:44)
只需使用splat(*)运算符,该运算符将元素数组扩展为可传递给方法的参数列表:
test_arr = [1, 3]
describe [1, 3, 7] do
it { should include(*test_arr) }
end
答案 1 :(得分:4)
如果您想断言子集数组的 order ,那么您需要做的不仅仅是should include(..)
,因为RSpec&#39} 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