You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel项目用Pest搭建SQLite内存测试数据库遇迁移问题

解决Laravel Pest测试中SQLite内存库迁移未执行的问题

1. 明确指定迁移的数据库连接与绝对路径

你的beforeAll调用未明确指定目标数据库连接,可能导致迁移执行在了默认连接而非sqlite_testing上。同时用绝对路径避免相对路径的上下文歧义:

beforeAll(function () {
    Artisan::call('migrate', [
        '--path' => base_path('tests/database/migrations'),
        '--database' => 'sqlite_testing',
        '--force' => true // 跳过生产环境保护提示,测试环境可安全使用
    ]);
});

2. 解决SQLite内存库的连接隔离问题

SQLite内存数据库的特性是每个数据库连接对应独立的内存实例,如果迁移时创建的连接和测试代码使用的连接不是同一个,测试就会找不到迁移后的表。

  • 先临时改用文件型SQLite验证迁移逻辑是否正常:修改config/database.php
    'sqlite_testing' => [
        'driver' => 'sqlite',
        'database' => database_path('testing.sqlite'),
        'prefix' => '',
    ],
    
    若测试能正常找到表,说明问题出在内存库的连接共享上。换回内存库后,确保全程复用同一个连接:
    use Illuminate\Support\Facades\DB;
    
    beforeAll(function () {
        // 提前获取连接实例,确保后续操作复用同一个内存库
        DB::connection('sqlite_testing')->getPdo();
        Artisan::call('migrate', [
            '--path' => base_path('tests/database/migrations'),
            '--database' => 'sqlite_testing',
            '--force' => true
        ]);
    });
    

3. 配置phpunit.xml简化迁移调用

在phpunit.xml中添加迁移路径的环境变量,无需每次在命令中重复指定:

<phpunit>
    <!-- 其他已有配置 -->
    <php>
        <env name="DB_CONNECTION" value="sqlite_testing"/>
        <env name="MIGRATION_PATH" value="tests/database/migrations"/>
    </php>
</phpunit>

之后beforeAll可简化为:

beforeAll(function () {
    Artisan::call('migrate', [
        '--database' => 'sqlite_testing',
        '--force' => true
    ]);
});

4. 适配自定义迁移路径的RefreshDatabase Trait

如果想自动处理迁移与测试后的回滚,可以自定义Trait覆盖默认逻辑:

namespace Tests\Traits;

use Illuminate\Foundation\Testing\RefreshDatabase;

trait CustomRefreshDatabase
{
    use RefreshDatabase;

    protected function migrateUsing()
    {
        return $this->artisan('migrate', [
            '--path' => base_path('tests/database/migrations'),
            '--database' => 'sqlite_testing',
        ]);
    }
}

在测试文件中直接使用该Trait即可自动完成迁移:

uses(Tests\Traits\CustomRefreshDatabase::class);

test('example user test', function () {
    // 测试逻辑,此时users表已完成迁移
});

内容的提问来源于stack exchange,提问作者mankowitz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:03:13