2013-01-08 40 views
17

我想要测试是否阵列包括另一个(rspec的2.11.0)rspec数组应包含哪些内容?另一个阵列

​​

这是结果 RSpec的规格/ 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 mehod no接受数组参数,这是避免“eval”的更好方法吗?

回答

31

只需使用splat(*)运算符,其扩展了元件的阵列到的参数的列表,其可以被传递给方法:

test_arr = [1, 3] 

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

非常有趣的联系 – GioM

+2

OMG!这是令人兴奋的......严重的是,这在规范中非常有用,我不知道#include支持的参数列表。谢谢! –

4

如果您想声明子集数组的订单,则需要执行因为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 
相关问题