Search⌘ K
AI Features

Using Mocks to Specify Behavior

Explore how to use mocks and test doubles in Rails testing to verify controller behavior during execution. Understand the role of mocks in setting expectations for method calls, ensuring units interact correctly, and writing fast, isolated tests. This lesson helps you learn to avoid brittle tests while maintaining clear, maintainable unit tests focused on behavior rather than final states.

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

Controller testing deprecation

Often, this kind of test makes sense given a relatively complex set of object interactions. We don’t exactly have that here, but we can use the controller as a reasonable stand-in. Some features of controller tests are deprecated in Rails 5. Still, we won’t touch any of the deprecated features, and we’ll test the controller as its own unit, without dependencies on any other code. We think using test doubles is still a potentially valid way of unit-testing logic in controllers.

Traditional controller tests

Traditional controller tests, the deprecated kind, often test whether the controller sets a particular instance variable to pass off to the view and gives it a value matching the incoming data. ...