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

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.