Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec how to test an argument data type passed to a method

I need to test the passed argument type is an integer. Here is my test spec:

require 'ball_spin'

RSpec.describe BallSpin do
  describe '#create_ball_spin' do
    subject(:ball_spin) { BallSpin.new }
    it 'should accept an integer argument' do
      expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Integer))
      ball_spin.create_ball_spin(5)
    end
  end
end

My code:

class BallSpin
  def create_ball_spin n
    "Created a ball spin #{n} times" if n.is_a? Integer
  end
end

Thanks in advance

UPDATE:

Apologize for using old RSpec syntax, below I updated my code to use the latest one:

it 'should accept an integer argument' do
  expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Integer))
  ball_spin.create_ball_spin(5)
end
like image 490
Kris MP Avatar asked Oct 17 '25 14:10

Kris MP


2 Answers

You may add a block to receive to check the method params:

expect(ball_spin).to receive(:create_ball_spin) do |arg|
  expect(arg.size).to be_a Integer
end

You may find details in Arbitrary Handling section of rspec-mocks documentation.

UPDATE: Also you may use the same approach with should syntax:

ball_spin.should_receive(:create_ball_spin) do |arg|
  arg.should be_a Integer
end
like image 187
Ilya Lavrov Avatar answered Oct 21 '25 14:10

Ilya Lavrov


I think the reason is that 5 is an instance of Fixnum and not Integer:

2.2.1 :005 > 5.instance_of?(Fixnum)
  => true 
2.2.1 :006 > 5.instance_of?(Integer)
  => false 

UPDATE: Ok, I've tried your code and the problem is Integer instead of Fixnum. Here is the correct assertion:

RSpec.describe BallSpin do
  describe '#create_ball_spin' do
    subject(:ball_spin) { BallSpin.new }
    it 'should accept an integer argument' do
      expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Fixnum))
      ball_spin.create_ball_spin(5)
    end
  end
end
like image 43
Antonio Ganci Avatar answered Oct 21 '25 13:10

Antonio Ganci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!