RSpec: Stub private method

The bad news is: you can not stub private method.

The good one is: you can make your method protected and then stub it the usual way;

allow_any_instance_of(described_class).to(
  receive(:my_protected_method_name).and_return("foo_bar")
)

You can use allow_any_instance_of method to stub or mock any instance of a class for e.g. you have a class named Foo with some private methods than you can do something like this

allow_any_instance_of(Foo).to receive(:private_method) do
  #do something
end 

In case if there you have module also, you can do something like this

allow_any_instance_of(Module::Foo).to receive(:private_method) do
  #do something
end

You can find more details about allow_any_instance_of() method at Official Documentation


Why do you want to test the private methods? They're private for a reason; to prevent access from external calls. Testing the public methods that rely on the private methods should be sufficient.


should_receive(:method) works whether the visibility of :method is public or private.