plannr/laravel-fast-refresh-database

比以往任何时候都更快地刷新您的数据库 🚀

v1.2.0 2024-04-08 11:29 UTC

This package is auto-updated.

Last update: 2024-09-08 12:21:59 UTC


README

你是否遇到过这样的情况,当你有大量迁移时,传统的RefreshDatabase特质需要花费很长时间来运行测试?如果是这样,你可能需要这个包!

问题

传统上,每次运行测试时,RefreshDatabase特质都会运行php artisan migrate:fresh。在第一次测试之后,它会使用事务来回滚数据并运行下一个测试,因此后续测试速度快,但第一次测试慢。如果你习惯于运行单个测试,这可能会非常烦人,因为它可能需要几秒钟来运行单个测试。

解决方案

你不需要在每次运行测试时都运行php artisan migrate:fresh,只有在添加新迁移或更改旧迁移时才需要。FastRefreshDatabase特质将创建你的migrations文件夹以及当前Git分支的校验和。然后,它将在应用程序的storage/app目录中创建一个校验和文件。当你的迁移更改或分支更改时,校验和不会匹配缓存的校验和,并且会运行php artisan migrate:fresh

当你没有进行任何更改时,它将继续使用相同的数据库而不会刷新,这可以加快测试时间100倍!

基准测试

运行单个测试,大约有400个迁移。

安装

使用Composer安装此包

composer require plannr/laravel-fast-refresh-database --dev

添加到您的TestCase中

接下来,只需将您的TestCase文件中使用的现有RefreshDatabase特质替换为FastRefreshDatabase特质。

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
-use Illuminate\Foundation\Testing\RefreshDatabase;
+use Plannr\Laravel\FastRefreshDatabase\Traits\FastRefreshDatabase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
-   use RefreshDatabase;
+   use FastRefreshDatabase;
}

使用Pest

只需替换您的Pest.php文件中的uses行。

-use Illuminate\Foundation\Testing\RefreshDatabase;
+use Plannr\Laravel\FastRefreshDatabase\Traits\FastRefreshDatabase;

-uses(RefreshDatabase::class)->in(__DIR__);
uses(FastRefreshDatabase::class)->in('Feature');

删除迁移校验和

有时你可能希望强制更新数据库迁移,为此,请在storage/app中找到migration-checksum_{Database Name Slug}.txt文件。

自定义校验和文件位置

你可以通过扩展特质并覆盖getMigrationChecksumFile()方法来自定义迁移校验和文件的位置和名称。

protected function getMigrationChecksumFile(): string
{
    return storage_path('custom/some-other-file.txt');
}

ParaTest 数据库

并行测试数据库包含作为每个测试运行器唯一标识符的令牌。这使得特质能够无需额外努力就内在地支持并行测试,因为数据库名称存储在校验和文件名中。