How to stub rand in rspec?

rand is indeed implemented in the Kernel module. However, when calling the method inside your code, the method receiver is actually your own object.

Assume the following class:

class MyRandom
  def random
    rand(10000..99999)
  end
end

my_random = MyRandom.new
my_random.random
# => 56789

When calling my_random.random, the receiver (i.e. the object on which the method is called on) of the rand method is again the my_random instance since this is the object being self in the MyRandom#random method.

When testing this, you can this stub the rand method on this instance:

describe MyRandom do
  let(:subject) { described_class.new }

  describe '#random' do
    it 'calls rand' do
      expect(subject).to receive(:rand).and_return(12345)
      expect(subject.random).to eq 12345
    end
  end
end

This works:

allow_any_instance_of(Object).to receive(:rand).and_return(12345)

Tags:

Ruby

Rspec