17

I want to check that an array contains only objects of a specific class, let's say Float.

A working example at the moment:

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

Is there a way to validate if the array_to_test contains only Float instances?

Sample non-working pseudocode:

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

Do not consider Ruby and Rspec version as a restriction.

potashin
  • 44,205
  • 11
  • 83
  • 107
Chris Lontos
  • 175
  • 2
  • 9

2 Answers2

37

Try all:

expect(array_to_test).to all(be_a(Float))
potashin
  • 44,205
  • 11
  • 83
  • 107
0

You could use ruby methods:

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

Or for better practice, implement a Helper using those methods:

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

and then use it this way:

expect(array_to_test) to all_be_same_type
Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Sergio Belevskij
  • 2,478
  • 25
  • 24