如何在 MiniTest 中存根带有参数的方法

How to stub a method with argument in MiniTest

我可以stub这样的方法:

def test_stale_eh
  obj_under_test = Something.new
  refute obj_under_test.stale?

  Time.stub :now, Time.at(0) do
    assert obj_under_test.stale?
  end
end

来自 http://www.rubydoc.info/gems/minitest/4.2.0/Object:stub

但我找不到有关如何对带有参数的方法进行存根的信息。 比如我想stub一个Time.parse方法,应该怎么写?

如果您希望结果始终相同(即存根方法的结果不依赖于参数),您可以将其作为值传递给 stub:

expected_time = Time.at(2)

Time.stub :parse, Time.at(2) do
  assert_equal expected_time, Time.parse("Some date")
end

如果你想return根据参数得到不同的结果,你可以传递一些可调用的东西。 The docs say:

If val_or_callable responds to #call, then it returns the result of calling it, otherwise returns the value as-is.

这意味着你可以像这个人为的例子那样做:

stub = Proc.new do |arg|
  arg == "Once upon a time" ? Time.at(0) : Time.new(2016, 9, 30)
end

Time.stub :parse, stub do
  assert_equal Time.new(2016, 9, 30), Time.parse("A long, long time ago")
  assert_equal Time.at(0), Time.parse("Once upon a time")
end