Mock Object behaviour on Real Objects

RSpec allows you to add mock object behaviour to real objects, so you can set message expectations and method stubs on any object in your system.

One common use of this support is isolating examples from ActiveRecord (and therefore the database) in Ruby on Rails examples.

MyModel.should_receive(:find).with(id).and_return(@mock_model_instance)

Controlling the behaviour of the class level methods (for example, having them return a mock object instead of a real instance of the model class) allows you to describe your controllers and views in isolation from the instance level logic of your model classes. This means that you can change the validation rules for a model, for example, and drive that in the model examples without affecting the controller and view examples.

This also helps to keep the context of your example completely in view (no having to look at fixtures/xyz.yml to understand what’s going on).