繁体   English   中英

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

[英]Rspec stubbing method for only specific arguments

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

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

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

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

您可以为fire!添加默认存根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)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM