繁体   English   中英

RSpec Stubbing:返回参数

[英]RSpec Stubbing: Return the parameter

虽然我的问题非常简单,但我在这里找不到答案:

如何存根方法并返回参数本身(例如,在执行数组操作的方法上)?

像这样的东西:

 interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)

注意:不推荐使用存根方法。 请参阅此答案 ,了解现代方法。


stub! 可以接受一个块。 该块接收参数; 块的返回值是存根的返回值:

class Interface
end

describe Interface do
  it "should have a stub that returns its argument" do
    interface = Interface.new
    interface.stub!(:get_trace) do |arg|
      arg
    end
    interface.get_trace(123).should eql 123
  end
end

存根方法已被弃用,有利于期望。

expect(object).to receive(:get_trace).with(anything) do |value| 
  value
end

https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation

您可以使用allow (stub)而不是expect (mock):

allow(object).to receive(:my_method_name) { |param1, param2| param1 }

使用命名参数:

allow(object).to receive(:my_method_name) { |params| params[:my_named_param] }

这是一个真实的例子:

假设我们有一个S3StorageService ,它使用upload_file方法将我们的文件上传到S3。 该方法将S3直接URL返回到我们上传的文件。

def self.upload_file(file_type:, pathname:, metadata: {}) …

我们想要存储上传的原因有很多(离线测试,性能改进......):

allow(S3StorageService).to receive(:upload_file) { |params| params[:pathname] }

该存根只返回文件路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM