4

I've tried Random.stub :rand, 1 do ... end and Kernel.stub :rand, 1 do ... end and Class.stub :rand, 1 do ... end (because when I run self.class where I run rand(2) I get Class). I've also tried replacing rand(2) with Random.rand(2) but it doesn't help.

So how do I stub out rand?

Camden Narzt
  • 2,271
  • 1
  • 23
  • 42

1 Answers1

7

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
Matt Brictson
  • 10,904
  • 1
  • 38
  • 43