2013-01-08 41 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 
相關問題