gpt4 book ai didi

ruby - 如何在 MiniTest 中 stub 带有参数的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:41 25 4
gpt4 key购买 nike

我可以 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 方法的信息。例如,如果我想 stub 一个 Time.parse 方法,我该如何编写它?

最佳答案

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

expected_time = Time.at(2)

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

如果你想根据参数返回不同的结果,你可以传递一些可调用的东西。 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

关于ruby - 如何在 MiniTest 中 stub 带有参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39782004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com