Using Mocks to Simulate Database Failure

A common use case for test doubles in Rails is to simulate database failures. Let’s look at how you might do that.

In the past, I would have suggested testing for failure at the controller level. However, Rails has basically deprecated controller tests for reasons I’ll talk about in Chapter 11, Testing Rails Display Elements, and so I’d like to stay within the bounds of Rails community behavior.

Let’s look at the project-creation functionality you wrote at the beginning of the book. You wrote a controller:

 def​ create
  @workflow =
 name: ​params[​:project​][​:name​],
 task_string: ​params[​:project​][​:tasks​])
  @workflow.create ...

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

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