DEV Community

Paul Preibisch
Paul Preibisch

Posted on

Speeds up Your Tests!

Great news! With a simple command

// Dump the current database and save it in database/schema
php artisan schema:dump

// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune
Enter fullscreen mode Exit fullscreen mode

You can greatly speed up your tests! Continue to find out more!

Hi everyone! These days I have been tasked to implement automated testing for a Laravel that had zero test coverage from the start.

As you probably know, Laravel's default testing behaviour is to use SQlLite, and in-memory database to run all tests against.

When building my first test however, I needed to ensure that my test database had data it could test against. So, I needed to use Laravel's RefreshDatabase Trait in my test.

The RefreshDatabase trait instructs laravel to run clear the testing database, and run all database migrations to set up the tables.

At this point in the development stage, we had about 50 migration files already, and some of them used MySql's DropColumn command which is incompatible with SQlLite.

To fix the problem, I edited the phpunit.xml file, and changed the server variables to point to a MySql testing database instead

 <server name="DB_CONNECTION" value="mysql"/>
 <server name="DB_DATABASE" value="testing"/>
 <server name="DB_USERNAME" value="testuser1"/>
 <server name="DB_PASSWORD" value="mypassword"/>
Enter fullscreen mode Exit fullscreen mode

I then re-ran the unit test, and it completed. Unfortunately, the test took 17 seconds to run! The culprit? You guessed it - the 50 migration files!

But then I got thinking - since the migration files are just a list of steps we took through our development iterations to get the database just perfect, why not just have one migration that creates the entire database in one fell swoop?

The next though I had was - wait - I bet I am not the only one that has thought of this solution! And sure enough, as of Laravel 8, there is a new console command that allows you to do just that:

// Dump the current database and save it in database/schema
php artisan schema:dump

// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune
Enter fullscreen mode Exit fullscreen mode

Now, the next time you run "php artisan migrate", the database will be set to the current state it was when you ran the schema dump, and then any other migrations after that point will also be run.

And guess what? My 17 second test now ran in 4 seconds! what a great improvement!

Top comments (1)

Collapse
 
alex86 profile image
AL

Thanks. I'll be adding this to my project.