RSpec Stubbing:返回参数
虽然我的问题非常简单,但我未能在这里找到答案:
如何存根方法并返回参数本身(例如在执行数组操作的方法上)?
像这样的东西:
interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)
Though my question is pretty straightforward, I failed to find an answer around here:
How can I stub a method and return the parameter itself (for example on a method that does an array-operation)?
Something like this:
interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:stub 方法已被弃用。请参阅此答案了解执行此操作的现代方法。
stub!
可以接受一个块。该块接收参数;块的返回值是存根的返回值:Note: The stub method has been deprecated. Please see this answer for the modern way to do this.
stub!
can accept a block. The block receives the parameters; the return value of the block is the return value of the stub:存根方法已被弃用,取而代之的是expect。
https://relishapp.com/rspec/rspec-mocks/ v/3-2/docs/configuring-responses/block-implementation
The stub method has been deprecated in favor of expect.
https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation
您可以使用
allow
(存根)而不是expect
(模拟):使用命名参数:
这是一个现实生活中的示例:
假设我们有一个
S3StorageService 使用
upload_file
方法将我们的文件上传到 S3。该方法返回我们上传文件的 S3 直接 URL。我们想要存根上传的原因有很多(离线测试、性能改进……):
该存根仅返回文件路径。
You can use
allow
(stub) instead ofexpect
(mock):With named parameters:
Here is a real life example:
Let's assume we have a
S3StorageService
that uploads our files to S3 using theupload_file
method. That method returns the S3 direct URL to our uploaded file.We want to stub that upload for many reasons (offline testing, performance improvements…):
That stub only returns the file path.