Final speed up for your Laravel test suite

RefreshDatabaseFast only runs migrate:fresh when your migration files changed, which drastically speeds up your Laravel test suite.

Zacharias Creutznacher Zacharias Creutznacher

In my current project I have about 200 migrations. Cause of incompatibility I can't use sqllite. Also I think it's always better to test against the database you're actually running on dev or production! So I went with mysql. I setted up the test suite with PHP Pest and started testing. After applying the RefreshDatabase trait to my tests I was shocked how** slow it became. Now everytime I do a test, it migrates all the 200 tables from new. But since all Laravel tests are transaction-based and are getting rolledback after the test is finished, there is really no need to migrate the whole table structure from scratch **every time you do a test.

#RefreshDatabaseFast to the rescue

Therefore we now add a new RefreshDatabaseFast trait to our laravel-useful-additions package. The base idea comes from Mayahi and we now wrapped it slightly changed and improved into our package.

This trait makes the migration of your database in your test suite much, much faster! It basically** only migrates your database if the migration files has changed**. So the first migrate:fresh takes a while (depending on how many migrations you have), and then it's incredibly fast.

Optionally you can set USEFUL_TRAITS_SEED_AFTER_FAST_DB_REFRESH to true if you like to seed your database after the migration.

Also make sure to add the .phpunit.database.checksum to your .gitignore file!

 1<?php
 2
 3/* 
 4 * ==================
 5 * For Pest - Pest.php
 6 * ==================
 7 */
 8
 9use LaracraftTech\LaravelUsefulTraits\RefreshDatabaseFast;
10
11uses(RefreshDatabaseFast::class);
12
13it('dose something', function() {
14    //...
15});
16
17/* 
18 * ==================
19 * For PHPUnit
20 * ==================
21 */
22
23use LaracraftTech\LaravelUsefulTraits\RefreshDatabaseFast;
24use Tests\TestCase;
25
26class MyTest extends TestCase
27{
28    use RefreshDatabaseFast;
29    
30    / **@test** /
31    public function it_does_something()
32    {
33        // ...
34    }
35}

#Comparison

If we now compare the first test run with the next one it's much faster! Cause we do not need to remigrate the whole (already existing) database!