StandardNerd
StandardNerd

Reputation: 4183

rspec check array elements for instances of numbers

How to check if the elements of arrays are containing only numbers (integers)?

 describe "#draw" do
   it "returns an array" do
     expect(@lottery_tip.draw).to be_a_kind_of Array
   end
   it "has six elements" do
     expect(@lottery_tip.draw.count).to eq(6)
   end
   it "s elements are only numbers" do
     expect(@lottery_tip.draw).to ???
   end
 end

My simple LotteryTip Class works but i'm wondering how to check the type of the elements in that returning array...

Upvotes: 3

Views: 2009

Answers (2)

iblue
iblue

Reputation: 30404

You can use the all matcher.

expect(@tip.draw).to all(be_an(Integer))

Upvotes: 7

StandardNerd
StandardNerd

Reputation: 4183

I'm not sure if this is best or at least good practice but i defined an own method in the before :each do block:

def is_number?
  @tip.all? { |x| x.is_a? Integer }
end

And so i can check in the it block:

   it "s elements are only numbers" do
     expect(is_number?).to eq(true)
   end

Upvotes: 0

Related Questions