Array Driven Model Tests in Laravel

Erik@ThriveMind Society
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 :)

Erik@ThriveMind Society

Written by

Software developer, philosopher, budding entrepreneur, exuberant expeller of thoughts and ideas. https://erikpwhite.com :: https://mindthrivesociety.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade