使用 Laravel Sail 和单独的测试数据库

Using Laravel Sail with a separate testing database

我正在使用 Laravel Sail 作为我的开发环境。根据 docs,

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

这非常适合我的开发环境,但在测试时效果不佳,因为我的 .env.testing 定义了一个单独的数据库,而且似乎没有创建该数据库 - 当我 sail mysql 放入容器中,运行 show databases; 未列出。结果,运行ning sail test 未能通过与数据库相关的每个测试。

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

我的 .env 文件包含:

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

我的 .env.testing 文件包含:

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

DB_USERNAMEDB_PASSWORD 在两个文件中相同。

如何创建此数据库以便在 运行宁 sail test 时可用?

编辑:

正如我挖掘 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.

将以下内容添加到 docker-compose.ymlservices: 键下,并将 .env.testing 中的主机设置为 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

您应该能够在现有 mysql 容器上与原始 dev 数据库一起创建 test 数据库:

sail mysql

mysql> CREATE DATABASE test;

我没有使用 mysql 对此进行测试,但同样的过程适用于 postgres:

sail psql

dev=# CREATE DATABASE test;