Mocks and Stubs Mocks and Stubs ruby ruby

Mocks and Stubs


My very simplified answer is:

  • mocks are objects that have a similar interface as something else
  • stubs are fake methods and return a specific answer

With both we are trying to achieve the same thing: we want to test a specific unit (model/view/controller/module) in isolation. E.g. when we are testing the controller, we do not want to test our model, so we use a mock. We want to make sure the correct methods are called, e.g. find. So on our mock, we have a stub that will return something predefined, without actually going to the database.

So we test for expectations: the methods that we expect to be called (on other units), without actually calling them. The test of that specific method, should have been covered in its own test.


According to Fowler's article mocks are not stubs, stubs are fake methods independent from outside calls, while mocks are fake objects with pre-programmed reactions to calls.

Mocking is more specific and object-related: if certain parameters are passed, then the object returns certain results. The behavior of an object is imitated or "mocked".

Stubbing is more general and method-related:a stubbed method usually returns always the same result for all parameters. The behavior of a method is frozen, canned or "stubbed".


Mocks are used in interaction-based testing to verify behavior. With a mock, you can assert that the method under test called another method. For example, I might want to make sure that a controller object calls a repository to get some data.

Stubs are used in state-based testing to set up a certain application state. Unlike mocks, you don't worry whether the call was made or not. For example, if you were testing some repository code, you might want to set up a stub method to make sure that the repository correctly handles the case when the database connection is closed.