2016-02-19 53 views
2

我想檢查一個數組只包含特定類的對象,比如說Float期望所有的數組元素是同一類

目前工作的示例:

it "tests array_to_test class of elements" do 
    expect(array_to_test.count).to eq(2) 
    expect(array_to_test[0]).to be_a(Float) 
    expect(array_to_test[1]).to be_a(Float) 
end 

有沒有辦法來驗證如果array_to_test只包含Float實例?

樣品不工作的僞代碼:

it "tests array_to_test class of elements" do 
    expect(array_to_test).to be_a(Array[Float]) 
end 

不考慮Ruby和Rspec的版本作爲限制。

回答

4

嘗試all

expect(array_to_test).to all(be_an(Float)) 
+0

是的,這就是它!看來我在文檔中找不到它... 感謝您的快速回復! –

0

寬例子 - 所有項目wiil是同一類: [ 「AAA」, 「VVV」, 「ZZZ」] =>真 [ 「AAA」,111,真] =>假

expect(array_to_test.map(&:class).uniq.length) to be_eq(1)

但寫測試助手爲更好:

RSpec::Matchers.define :all_be_same_type do match do |thing| thing.map(&:class).uniq.length == 1 end end

和:

expect(array_to_test) to all_be_same_type

相關問題