【问题标题】:Rspec stubbing method for only specific arguments仅针对特定参数的 Rspec 存根方法
【发布时间】:2012-04-02 08:17:00
【问题描述】:

有没有办法只为特定参数存根方法。像这样的

boss.stub(:fire!).with(employee1).and_return(true)

如果将任何其他员工传递给boss.fire! 方法,我会得到boss received unexpected message 错误,但我真正想要的只是覆盖特定参数的方法,并将其留给所有其他人。

有什么想法可以做到这一点吗?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您可以为 fire! 方法添加一个默认存根,该方法将调用原始实现:

    boss.stub(:fire!).and_call_original
    boss.stub(:fire!).with(employee1).and_return(true)
    

    Rspec 3 语法 (@pk-nb)

    allow(boss).to receive(:fire!).and_call_original
    allow(boss).to receive(:fire!).with(employee1).and_return(true)
    

    【讨论】:

    • 与 RSpec 3 语法相同:allow(boss).to receive(:fire!).and_call_original allow(boss).to receive(:fire!).with(employee1).and_return(true)
    • 请注意,您不能将一个通用allow 与一个特定expect 组合在一起。
    【解决方案2】:

    您可以尝试编写自己的存根方法,使用类似这样的代码

    fire_method = boss.method(:fire!)
    boss.stub!(:fire!) do |employee|  
      if employee == employee1
        true
      else
        fire_method.call(*args)
      end
    end
    

    【讨论】:

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