Array Driven Model Tests in Laravel

May 31, 2019 · 2 min read
Image for post
Image for post
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 :)

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store