rand
is part of the Kernel
module that is mixed into every class. To stub it, you need to call stub
on the object where rand
is being called.
It's probably easiest to see in an example. In the following code, rand
is a private instance method of the Coin
, because Coin
implicitly inherits from Object
and Kernel
. Therefore I need to stub on the instance of Coin
.
require "minitest/autorun"
require "minitest/mock"
class Coin
def flip
rand(0..1) == 1 ? "heads" : "tails"
end
end
class CoinTest < Minitest::Test
def test_flip
coin = Coin.new
coin.stub(:rand, 0) do
assert_equal("tails", coin.flip)
end
end
end