Dedicated test databases with Laravel Sail

Run your tests in separate database with Laravel Sail

I’ve been playing around with Laravel Sail on a project that I’ve just started and wanted to be able to run my tests on a separate database and leave my main DB intact for development.

Adding a second database for tests involves adding a second container and configuring your tests to point at the newly created host.

Add the following to docker-compose.yml under the services: key:

mysql_test:
  image: "mysql:8.0"
  environment:
    MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
    MYSQL_DATABASE: "${DB_DATABASE}"
    MYSQL_USER: "${DB_USERNAME}"
    MYSQL_PASSWORD: "${DB_PASSWORD}"
    MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
  networks:
    - sail

Next, configure your .env.testing file to point at the mysql_test host (Docker Compose uses the service name as the host name for networking):

# Don't forget to set APP_KEY too
DB_HOST=mysql_test # This is the important bit
DB_DATABASE=
DB_USERNAME=root

Then finally, run your tests:

./vendor/bin/sail test