Using Mocks to Specify Behavior

In addition to merely replacing expensive method calls, mock objects enable a different style of testing where you validate the application’s behavior rather than its ending state. In most of the tests we’ve seen throughout the book, the test validates the result of a computation: it’s testing whether something is true at the end of an action. When using mocks, however, we have the opportunity to test the process’s behavior during the test rather than the outcome.

Let’s look at an example. Back in Who Controls the Controller?, we wrote the following test of our ProjectsController:

mocks/01/gatherer/spec/controllers/projects_controller_spec.rb
 
it ​"creates a project"​ ​do
 
post :create, project: {name: ​

Get Rails 4 Test Prescriptions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.