问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/31600968/how-can-i-stub-rand-in-minitest