Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to unstub in RSpec?

Tags:

ruby

rspec

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

Is this possible?

like image 254
B Seven Avatar asked Apr 23 '13 17:04

B Seven


People also ask

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet. Here is the code from the section on RSpec Doubles − class ClassRoom def initialize(students) @students = students End def list_student_names @students.

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.


2 Answers

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.

like image 79
elado Avatar answered Sep 21 '22 13:09

elado


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 
like image 28
fmendez Avatar answered Sep 18 '22 13:09

fmendez