简体   繁体   English

我怎么能在最小的时候留下兰特?

[英]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 ... endKernel.stub :rand, 1 do ... endClass.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. randKernel模块的一部分,它被混合到每个类中。 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 . 在下面的代码中, randCoin的私有实例方法,因为Coin隐式继承自ObjectKernel 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM