ruby - How to stub rand in rspec? -


i'm using ruby 2.3.4 , rspec 3.6.0.

i'm writing test object uses rand(10000..99999). can't find docs on rand see object it's part of. tried stubbing kernel, object, , random (see below) none of attempts resulted in rand being stubbed object.

allow(kernel).to receive(rand).and_return(12345) allow(object).to receive(rand).and_return(12345) allow(random).to receive(rand).and_return(12345) 

any appreciated.

rand indeed implemented in kernel module. however, when calling method inside code, method receiver own object.

assume following class:

class myrandom   def random     rand(10000..99999)   end end  my_random = myrandom.new my_random.random # => 56789 

when calling my_random.random, receiver (i.e. object on method called on) of rand method again my_random instance since object being self in myrandom#random method.

when testing this, can stub rand method on instance:

describe myrandom   let(:subject) { described_class.new }    describe '#random'     'calls rand'       expect(subject).to receive(:rand).and_return(12345)       expect(subject.random).to eq 12345     end   end end 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -