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

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.