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 allow and receive methods.

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


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

As well as the stub replacing mock result possible with and_return


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 double method.

In the example above we are using fake double object created to replace API call inside UpdateObject 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 double with instance_double, 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