Automatically Running Migrations with Laravel 5 Tests

  • June 24, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

It is crucial for you to ensure that your database structure and test data are in a known state prior to the execution of each and every test, otherwise you're likely to introduce all sorts of uncertainty into the very situations you're trying to verify. One foolproof way to do this is by completely tearing down and rebuilding your test database structure prior to and following each test, respectively. In this blog post I'll show you just how easy it is to repeatedly run your migrations in Laravel 5.1.

In prior versions of the book I showed you a fairly involved solution for doing automatically tearing down and rebuilding your migrations, however as of Laravel 5.1 it is a trivial task! All you need to do is add the following use DatabaseMigrations statement to your test class:


use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\Todolist;

class TodolistTest extends TestCase

    use DatabaseMigrations;


Once declared, Laravel will automatically rollback and execute your migrations for each and every test!