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

Mil*_*vic 42 ruby rspec

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

boss.stub(:fire!).with(employee1).and_return(true)
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*nih 65

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

boss.stub(:fire!).and_call_original
boss.stub(:fire!).with(employee1).and_return(true)
Run Code Online (Sandbox Code Playgroud)

Rspec 3语法(@ pk-nb)

allow(boss).to receive(:fire!).and_call_original
allow(boss).to receive(:fire!).with(employee1).and_return(true)
Run Code Online (Sandbox Code Playgroud)

  • RSpec 3语法也是一样:`allow(boss).to receive(:fire!).and_call_original allow(boss).to(:fire!).with(employee1).and_return(true)` (12认同)