23

虽然我的问题很简单,但我没能在这里找到答案:

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

像这样的东西:

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

3 回答 3

30

注意:存根方法已被弃用。请参阅此答案以了解执行此操作的现代方法。


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
于 2011-05-09T14:55:57.357 回答
21

存根方法已被弃用,取而代之的是期望。

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

于 2015-02-26T18:31:26.890 回答
5

您可以使用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将文件上传到 S3 的upload_file方法。该方法将 S3 直接 URL 返回到我们上传的文件。

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

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

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

该存根仅返回文件路径。

于 2017-06-23T13:58:52.387 回答