当我想验证 mock 是否发送了预期的参数时,我可以这样做
@mock.expect(:fnc, nil, ["a, "b"])
但是,如果我想模拟的类看起来像这样
class Foo
def fnc a:, b:
end
end
我如何模拟它并验证作为 a:
、b:
传递的值?
最佳答案
下面是我公司代码库中的一个真实示例:
mailer = MiniTest::Mock.new
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
true
end
mailer.deliver template_name: "xxx", data: {}, to: [], subject: "yyy"
如果您还想验证参数的类型:
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
template_name.is_a?(String) &&
data.is_a?(Hash) &&
to.is_a?(Array) &&
subject.is_a?(String) &&
end
更新时间 2022-05-22
如果您在 Ruby v3 中使用此策略,您将得到 ArgumentError
。
我已经在这里提交了一个 PR 来解决这个问题:
https://github.com/minitest/minitest/pull/908
如果您希望在 Ruby v3 中使用此功能,请留下一些评论以引起项目所有者的注意。
更新2022-06-28
minitest 从 v5.16.0 开始支持关键字参数 🎉
https://github.com/minitest/minitest/blob/master/History.rdoc#5160--2022-06-14-
关于ruby - minitest - 模拟 - 期望关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43494606/