Using Laravel Sail with a separate testing database

Viewed 2924

I'm using Laravel Sail as my development environment. According to the docs,

when the MySQL container is starting, it will ensure a database exists whose name matches the value of your DB_DATABASE environment variable.

This works perfectly for my development environment, but not so much when it comes to testing since my .env.testing defines a separate database, and it seems this database does not get created - when I sail mysql into the container and run show databases; it is not listed. As a result, running sail test fails every test where the database is concerned.

SQLSTATE[HY000] [1045] Access denied for user ...

My .env file contains this:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=dev

My .env.testing file contains this:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=test

DB_USERNAME and DB_PASSWORD are the same in both files.

How can I create this database so that it's available when running sail test?

EDIT:

As I dug through the repository code I found that the database is being created when the mysql container image is built, but it doesn't look like there's an option for creating multiple databases.

MYSQL_DATABASE This variable is optional and allows you to specify the name of a database to be created on image startup. If a user/password was supplied (see below) then that user will be granted superuser access (corresponding to GRANT ALL) to this database.

2 Answers

Add the following to docker-compose.yml under the services: key and set your host in .env.testing to mysql_test:

  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

You should be able to create the test database alongside the original dev database on the existing mysql container:

sail mysql

mysql> CREATE DATABASE test;

I have not tested this using mysql but the same process works on postgres:

sail psql

dev=# CREATE DATABASE test;
Related