[英]How can I stub rand in minitest?
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
). 我试过
Random.stub :rand, 1 do ... end
和Kernel.stub :rand, 1 do ... end
和Class.stub :rand, 1 do ... end
(因为当我运行self.class
我跑rand(2)
我得到Class
。 I've also tried replacing rand(2)
with Random.rand(2)
but it doesn't help. 我也尝试用
Random.rand(2)
替换rand(2)
,但它没有帮助。
So how do I stub out rand? 那么我该怎么把兰德剔除?
rand
is part of the Kernel
module that is mixed into every class. rand
是Kernel
模块的一部分,它被混合到每个类中。 To stub it, you need to call stub
on the object where rand
is being called. 要存根它,您需要在调用
rand
的对象上调用stub
。
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
. 在下面的代码中,
rand
是Coin
的私有实例方法,因为Coin
隐式继承自Object
和Kernel
。 Therefore I need to stub on the instance of Coin
. 因此,我需要在
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.