How to create a test database with Laravel Sail
I have worked on projects that required the production and testing database to be the same.
This could be because some features work in MariaDB, but not in SQLite. Or some bugs appear in MySQL, but not in PostgreSQL.
When you're working in a large project, you need to know that the testing database works exactly like the one in production. You can't allow a bug to appear in production because the test database was different.
Note: If the project is small, chances are you are fine using SQLite for testing.
Today, I'm going to guide you through setting up a testing database in your current database server, thanks to Laravel Sail.
Before we start
This tutorial uses PostgreSQL as the database. But the idea is the same for any other database: create a separate database in your current database server.
- Laravel 9
- Laravel Sail
We will use the database server declared in the
In this case, PostgreSQL.
First, enter PostgreSQL's CLI
Note: If you are using MySQL, you can use
Now, create a new database
CREATE DATABASE testing;
This database is separated from the default database that your application uses.
Now, modify the
phpunit.xml file to use the new database and database server.
Should end up similar to this:
<env name="DB_CONNECTION" value="pgsql"/>
<env name="DB_DATABASE" value="testing"/>
Run the tests
Now, you can run the tests and see if they work.
sail test --parallel
It should look similar to this:
Tests: 1 passed
That was it. It's a one-time setup, that works like a charm.
If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰
Congratulations, today you have learned how to create a test database in Laravel Sail.
Without needing to modify the
docker-compose.yml file or creating more services.
Let me know if the tutorial was useful to you in the comments!