A Better way to Organize Tests in Laravel

May 29, 2019 · 2 min read
Image for post
Image for post
Organization is an utmost priority to any ( good ) programmer

Reduce, Reuse, and Recycle!

You probably already recognize Laravel as a flagship framework in the modern developer ecosystem. One of the best macro-features that Laravel offers to developers is various abilities for ‘World Building’.

Exceptional world building, or application initialization, is seen in the two spheres of testing and actual data.

Today I will quickly display how world building can vastly improve your application tests. The inspiration for this article is coming from two places: beloved Laracasts, and an article from Tighten ( at https://tighten.co/blog/tidy-up-your-tests-with-class-based-model-factories ). To learn this on a more in-depth level, either follow those two sources or contact me for deeper training.

Image for post
Image for post
What it feels like to create a Laravel App

As the title from the Tighten article says, we are going to be creating our test environment using a Factory Class ( Facade ). The significance of this is as such:

Concatenate this:

Image for post
Image for post
Taken from Laracast’s TDD tutorial

3 step process:

  1. create and sign-in a user
  2. create a project, owned by the authenticated user
  3. give the project a task

Into this:

Image for post
Image for post
One liners aren’t only for Action Movie heroes

Under the hood of the Factory Class, the same operations are being done. However, it is all being abstracted into one location. This is where the real significance lies. Instead of having to repeat the same code in every. single. test. function.. you can dynamically handle creating the necessary test environment. After all, code re-usage and efficiency is a cornerstone of programming.

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