2016-02-19 56 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

相关问题