Cis*_*tin 5 ruby unit-testing rspec ruby-on-rails
我的一个文件中有以下内容spec:
expect(my_instance).to receive(:my_function).with(arg: instance_of(String))
Run Code Online (Sandbox Code Playgroud)
我希望能够捕获我arg可以在规范中使用的变量的实际值。有没有办法做到这一点?我检查了 rspec 文档,但没有找到类似的内容。
您可以在(或,如果您不希望它在未收到时失败)captured_arg之前声明该变量。然后,您可以将参数收集在一个块中并在该块内进行设置。expectallowmy_instancemy_functioncaptured_arg
captured_arg = nil
expect(my_instance).to receive(:my_function) { |arg| captured_arg = arg }
Run Code Online (Sandbox Code Playgroud)
编辑:(关键字参数)
如果您使用关键字参数,只需稍微修改上面的脚本,用作arg您想要捕获的关键字参数:
captured_arg = nil
expect(my_instance).to receive(:my_function) { |args| captured_arg = args[:arg] }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1576 次 |
| 最近记录: |