Gio*_*ioM 24 arrays testing rspec
我试图测试一个数组是否包含另一个(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
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
包含rspec mehod不接受数组参数,这是避免"eval"的更好方法吗?
Chr*_*erg 48
只需使用splat(*)运算符,它将元素数组扩展为可以传递给方法的参数列表:
test_arr = [1, 3]
describe [1, 3, 7] do
it { should include(*test_arr) }
end
Run Code Online (Sandbox Code Playgroud)
如果要声明子集数组的顺序,则需要做更多的事情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
Run Code Online (Sandbox Code Playgroud)