51

Searched the Relish docs, but did not find a way to unstub in RSpec.

Is this possible?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
B Seven
  • 44,484
  • 66
  • 240
  • 385

2 Answers2

129

With new expect syntax, unstub is deprecated. You can do:

# stub
allow(SomeClass).to receive(:a_method)

# do something...

# unstub
allow(SomeClass).to receive(:a_method).and_call_original

If the first allow contains .with or a block, I believe it'll still carry to the next call, so the next allow doesn't clear those things.

elado
  • 8,510
  • 9
  • 51
  • 60
  • 2
    Thanks for this. Do you have reference to this documentation or location in the code? – steel Sep 12 '14 at 17:56
  • 3
    this should be marked as correct answer for rails 4 rspec 3.0 – andre.orvalho Nov 11 '14 at 20:49
  • Docs for version Rspec 3. https://relishapp.com/rspec/rspec-mocks/docs/configuring-responses/calling-the-original-implementation – counterbeing Aug 26 '15 at 22:34
  • Note that you probably want to do this in an `ensure` (or `after :each`) block. – David Moles Sep 03 '15 at 17:51
  • This is not working for me. When I do so, the previous stub remains and the test is failing stating "expected: 0 times with any arguments, received: 1 time with arguments: ("Masterfile")"... – ZedTuX Nov 15 '16 at 13:47
26

The rspec-mock code indicate that you can call the unstub method. I quote:

  # Removes a stub. On a double, the object will no longer respond to
  # `message`. On a real object, the original method (if it exists) is
  # restored.
  #
  # This is rarely used, but can be useful when a stub is set up during a
  # shared `before` hook for the common case, but you want to replace it
  # for a special case.
  def unstub(message)
    ::RSpec::Mocks.space.proxy_for(self).remove_stub(message)
  end
fmendez
  • 7,250
  • 5
  • 36
  • 35