Scaffolding Laravel tests
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
I've been a big fan of forced resourcefulness – that is to ensure your controllers map to a single resource only and have exposed at most the 7 resourceful actions; index
, create
, store
, show
, edit
, update
, destroy
(or similar, depending on what framework you're using).
There are many benefits to writing your apps this way, including keeping your code organised, your classes shorter and cleaner and easier to navigate. In addition it also allows you to scaffold the CRUD logic relatively easy. Not in the sense of using controller generators (not ruling that out, though), but that the core logic in a CRUD controller generally matches a pattern.
The index
action will get a collection of the resource and return a view. The create
action will return a view. The store
action will validate a request, create a resource and redirect. The show
and edit
actions will fetch a resource and return a view. The update
action will validate a request, fetch and update a resource and redirect. The destroy
action will fetch and destroy a resource and redirect. Simple.
As an example of a resourceful controller let's take a look at the PostsController.php
that I put together as part of my gold-standard
repository. It's a demonstration (at the most basic level) how a controller would fulfil the requirements of all 7 actions.
When writing new controllers I often follow this scaffold so that my code is clean and predictable. You completely cover the necessary actions of a resource in just under 100 lines. If we take this approach to scaffolding/templating our resourceful controllers we can take this one step further as well - apply it to our tests.
Now let's take a look at PostsControllerTest.php
also in the gold-standard
repository. This template provides tests for all 7 actions and their expected outcomes, including validation errors when creating and updating a resource.
You can see that the template is pretty simple, and not much longer than the controller itself. It utilises model factories to interact with actual models and generate model attributes on the fly. It hits the database hard and fast to actually test the application is working how you expect.
For the most part it's easy to see how you can re-purpose a scaffold like this when working with a resourceful controller. If you're using Artisan commands or Sublime Text/whatever text editor you use snippets to generate controller code, consider doing the same with your tests.
Write tight resourceful controllers and you can drop in these resourceful controller tests with little customisation to get them green and give you confidence that your app works.