期望所有的数组元素都是同一类别。

17

我想检查一个数组是否只包含特定类别的对象,比如说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的版本视为限制。

2个回答

37
尝试使用 all
expect(array_to_test).to all(be_a(Float))

是的,就是这样!看来我只是在文档中找不到它......感谢您的快速回复! - Chris Lontos

0

你可以使用Ruby方法:

expect(array_to_test.map(&:class).uniq.length) to 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接