Using Mocks to Simulate Rails Save

You can use mock objects to rectify what used to be a nagging annoyance in the standard Rails scaffolds (well, it annoyed me). The Rails-generated tests for a scaffolded controller created with rails generate scaffold controller do not cover the failure conditions for create and update. I’ve always assumed, with no real justification, this oversight was because the easiest way to test these is with a mock package and the Rails team didn’t want to mandate one particular package.

We’ve already mandated a mock package. And we’ve already written a failure test for ProjectController#create (see Testing for Failure). But if you’ll recall, we had to think of a case in which the save would fail. (The RSpec-generated ...

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.