DEV Community

Cover image for How to create a test database with Laravel Sail
Alejandro Akbal
Alejandro Akbal

Posted on • Originally published at blog.akbal.dev

How to create a test database with Laravel Sail

Introduction

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.

Preface

Requirements

  • Laravel 9
  • Laravel Sail

Database setup

We will use the database server declared in the docker-compose.yml file.
In this case, PostgreSQL.

services:
  pgsql:
    image: 'postgres:14'
Enter fullscreen mode Exit fullscreen mode

First, enter PostgreSQL's CLI

sail psql
Enter fullscreen mode Exit fullscreen mode

Note: If you are using MySQL, you can use sail mysql instead.

Now, create a new database

CREATE DATABASE testing;
Enter fullscreen mode Exit fullscreen mode

This database is separated from the default database that your application uses.


PHPUnit configuration

Now, modify the phpunit.xml file to use the new database and database server.
Should end up similar to this:

<php>
    <env name="DB_CONNECTION" value="pgsql"/>
    <env name="DB_DATABASE" value="testing"/>
</php>
Enter fullscreen mode Exit fullscreen mode

Run the tests

Now, you can run the tests and see if they work.

sail test --parallel
Enter fullscreen mode Exit fullscreen mode

It should look similar to this:

   PASS  Tests\Unit\ExampleTest
  ✓ example

  Tests:  1 passed
  Time:   0.7s
Enter fullscreen mode Exit fullscreen mode

End

That was it.
It's a one-time setup, that works like a charm.

Self-promotion

If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰

Conclusion

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!

Top comments (0)