如何在rspec中保存变量?

时间:2017-04-18 16:27:34

标签: ruby-on-rails ruby unit-testing rspec

我的一个spec文件中包含以下内容:

expect(my_instance).to receive(:my_function).with(arg: instance_of(String))

我希望能够在我可以在规范中使用的变量中捕获arg的实际值。有没有办法做到这一点?我检查了rspec文档,但没有找到类似的东西。

1 个答案:

答案 0 :(得分:2)

您可以在captured_arg(或expect之前声明allow之前声明变量,如果my_instance未收到my_function则不希望失败captured_arg 1}})。然后,您可以收集块中的参数并在该块中设置captured_arg = nil expect(my_instance).to receive(:my_function) { |arg| captured_arg = arg }

arg

编辑:(关键字参数)

如果您使用keyword arguments,只需稍微修改上面的脚本,使用captured_arg = nil expect(my_instance).to receive(:my_function) { |args| captured_arg = args[:arg] } 作为您要捕获的关键字参数:

composer.json