【发布时间】:2012-04-02 08:17:00
【问题描述】:
有没有办法只为特定参数存根方法。像这样的
boss.stub(:fire!).with(employee1).and_return(true)
如果将任何其他员工传递给boss.fire! 方法,我会得到boss received unexpected message 错误,但我真正想要的只是覆盖特定参数的方法,并将其留给所有其他人。
有什么想法可以做到这一点吗?
【问题讨论】:
有没有办法只为特定参数存根方法。像这样的
boss.stub(:fire!).with(employee1).and_return(true)
如果将任何其他员工传递给boss.fire! 方法,我会得到boss received unexpected message 错误,但我真正想要的只是覆盖特定参数的方法,并将其留给所有其他人。
有什么想法可以做到这一点吗?
【问题讨论】:
您可以为 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)
【讨论】:
allow(boss).to receive(:fire!).and_call_original allow(boss).to receive(:fire!).with(employee1).and_return(true)
allow 与一个特定expect 组合在一起。
您可以尝试编写自己的存根方法,使用类似这样的代码
fire_method = boss.method(:fire!)
boss.stub!(:fire!) do |employee|
if employee == employee1
true
else
fire_method.call(*args)
end
end
【讨论】: