Rspec存根方法仅适用于特定参数

时间:2012-04-02 08:17:00

标签: ruby rspec

有没有办法只针对特定参数的存根方法。像这样的东西

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

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

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:64)

您可以为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)

答案 1 :(得分:2)

您可以尝试编写自己的存根方法,使用此代码

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