开发者

RSpec Stubbing: Return the parameter

Though my question is pretty straightforward, I failed to find an answer around here:

How 开发者_Go百科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>)


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:

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


The stub method has been deprecated in favor of expect.

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


You can use allow (stub) instead of expect (mock):

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

With named parameters:

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

Here is a real life example:

Let's assume we have a S3StorageService that uploads our files to S3 using the upload_file method. That method returns the S3 direct URL to our uploaded file.

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

We want to stub that upload for many reasons (offline testing, performance improvements…):

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

That stub only returns the file path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜