将Laravel Sail与单独的测试数据库一起使用 [英] Using Laravel Sail with a separate testing database

查看:63
本文介绍了将Laravel Sail与单独的测试数据库一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

启动MySQL容器时,它将确保存在名称与您的DB_DATABASE环境变量的值匹配的数据库.

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 定义了一个单独的数据库,而且似乎没有创建该数据库-当我将 mysql 放入容器并运行 show database; ,但未列出.结果,在与数据库有关的每个测试中,运行 sail test 都会失败.

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 ...

我的 .env 文件包含以下内容:

My .env file contains this:

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

我的 .env.testing 文件包含以下内容:

My .env.testing file contains this:

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

两个文件中的

DB_USERNAME DB_PASSWORD 相同.

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

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

当我浏览存储库代码时,我发现当 mysql 容器映像已构建,但是它似乎没有创建选项多个数据库.

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 该变量是可选的,并允许您指定要在映像启动时创建的数据库的名称.如果提供了用户名/密码(请参阅下文),则将授予该用户对该数据库的超级用户访问权限(对应于GRANT ALL).

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.

推荐答案

services:键下,将以下内容添加到 docker-compose.yml 中,并将主机设置为 .env.testing mysql_test :

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

这篇关于将Laravel Sail与单独的测试数据库一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆