【问题标题】:Expect all array elements to be of the same class期望所有数组元素属于同一类
【发布时间】:2016-02-19 12:34:13
【问题描述】:

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

【问题讨论】:

    标签: arrays ruby testing rspec


    【解决方案1】:

    试试all:

    expect(array_to_test).to all(be_a(Float))
    

    【讨论】:

    • 是的,就是这样!看来我只是在文档中找不到它...感谢您的快速回复!
    【解决方案2】:

    你可以使用 ruby​​ 方法:

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

    或者为了更好的实践,使用这些方法实现一个 Helper:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2015-02-27
      • 2021-03-26
      • 2014-01-03
      • 2019-09-04
      相关资源
      最近更新 更多