Array Driven Model Tests in Laravel

Erik@MetaLevel
2 min readMay 31, 2019

--

The finished example with two models being tested

Following along with Laracasts TDD series, I found a neat little shortcut to writing the model tests for required fields that you may find useful. I didn’t want to repeat the code that Jeffrey used in 3= separate functions to create a project via factory with a single specific field empty, then assert if it had errors. Also, as a proper natural born programmer my instincts don’t allow me to simply mindlessly follow along a tutorial without thinking that I should do something better than how I’m being showed.

Thus, an array-driven approach to testing model requirements was born.

This is fairly straight forward as I am simply pre-defining an array of fields that the model marked as required, then looping through each attribute to create a project with that exact field blank, then asserting whether or not the session had any problems with it. Same as Jeffrey did on an individual basis.

Where this gets cool, is that I then extended this to test another Model that has a relationship to the first Model. In this app, ‘Tasks’ belong to ‘Projects’. Tasks also have required fields, so I first create a project, then while looping through each field I make sure to associate the task because updating the task is done through the relationship of the project.

Hope this helps :)

--

--