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 = CreatesProject.new(
 name: ​params[​:project​][​:name​],
 task_string: ​params[​:project​][​:tasks​])
  @workflow.create ...

Get Rails 5 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.