2017-04-18 34 views
2

我有大意如下的东西在我spec文件之一:如何在rspec期望保存一个变量?

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

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

回答

2

你可以声明变量,说captured_argexpect之前(或allow,如果你不希望它如果my_instance没有收到my_function失败)。然后您可以收集块中的参数并在该块内设置captured_arg

captured_arg = nil 
expect(my_instance).to receive(:my_function) { |arg| captured_arg = arg } 

编辑:(关键参数)

如果使用keyword arguments,只需修改上面的脚本咯,使用arg作为关键字参数,你想拍摄:

captured_arg = nil 
expect(my_instance).to receive(:my_function) { |args| captured_arg = args[:arg] }