【问题标题】:RSpec Stubbing: Return the parameterRSpec Stubbing:返回参数
【发布时间】:2011-08-21 17:40:58
【问题描述】:

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

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

类似这样的:

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

【问题讨论】:

    标签: ruby parameters rspec return-value stubbing


    【解决方案1】:

    注意:stub 方法已被弃用。请参阅this answer 了解执行此操作的现代方式。


    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
    

    【讨论】:

    • 谢谢,这正是我想要的!我知道答案一定很简单:)
    • @SirLenzOrlot,不客气!感谢您的复选标记,祝您黑客愉快。
    • 这个可以和sequence起作用的情况结合(比如第一次调用返回参数,下一次返回“disconnected”)?
    • @Sir,是的,但这似乎不是一种简单的方法。为什么不直接指定它应该接收(例如)“foo”并返回“foo”,然后接收“bar”并返回“disconnected”?
    • 我在stackoverflow.com/questions/7754733/…得到了两个答案
    【解决方案2】:

    存根方法已被期望弃用。

    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而不是expect吗?
    • @MarkoAvlijaš 仅当您不想设置调用该方法的期望时。
    【解决方案3】:

    您可以使用allow(存根)代替expect(模拟):

    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] }
    

    那个存根只返回文件路径。

    【讨论】:

      猜你喜欢
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多