51

Is there a way to stub method for only specific arguments. Something like this

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

If any other employee is passed to boss.fire! method, I'll get boss received unexpected message error, but what I would really like is just to override the method for specific argument, and leave it be for all others.

Any ideas how this can be done?

Milovan Zogovic
  • 1,541
  • 2
  • 16
  • 24

2 Answers2

81

You can add a default stub for the fire! method which will call original implementation:

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

Rspec 3 Syntax (@pk-nb)

allow(boss).to receive(:fire!).and_call_original
allow(boss).to receive(:fire!).with(employee1).and_return(true)
lulalala
  • 17,572
  • 15
  • 110
  • 169
Andrey Chernih
  • 3,513
  • 2
  • 27
  • 27
  • 12
    Same thing with RSpec 3 syntax: `allow(boss).to receive(:fire!).and_call_original allow(boss).to receive(:fire!).with(employee1).and_return(true)` – pk-nb May 07 '15 at 17:31
  • Note that, you cannot combine one generic `allow` with one specific `expect`. – lulalala Jan 13 '20 at 09:15
4

You can try write your own stubbing method, with code like this

fire_method = boss.method(:fire!)
boss.stub!(:fire!) do |employee|  
  if employee == employee1
    true
  else
    fire_method.call(*args)
  end
end
kr00lix
  • 3,284
  • 1
  • 17
  • 11