How can I stub rand in minitest?

一笑奈何 提交于 2019-12-12 12:12:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!