Difference between Mocks and Stubs in RSpec

What is the difference, how and when to apply?


A stub is the only defined result of the method call which doesn’t care about behavior. With RSpec, you can use stub with and methods.

allow(object).to receive(:method_name)

If you need to stub the result of the method then it’s possible with

allow(object).to receive(:method_name).and_return(example_value)


Mock expect methods to be called, otherwise it raises an error. With RSpec, you can use mock with and methods.

expect(object).to receive(:method_name)

As well as the stub replacing mock result possible with

expect(object).to receive(:method_name).and_return(example_value)


Test double is a dummy object that you use to replace a real object during a test. Through RSpec, you can create it with the method.

describe UpdateObject do
let(:external_api) { double }
before do
allow(ExternalApi).to recieve(:new).and_return(external_api)
allow(external_api).to recieve(:some_api_call)
it 'returns success' do
expect(subject.call).to eq(:success)

In the example above we are using fake object created to replace API call inside and avoid dependence of the test on the work of an external service.

If you want to create a more specified test, you can replace with , which will fail tests if the class or object doesn’t have used methods.

Software Engineer. Interested in Full-Stack Development and DevOps.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store