我有一个 Laravel 5.4 项目,正在尝试使用 Dusk 运行一些测试。我想在运行测试之前重置、迁移和播种。我已经将它设置为使用 SQLite,理想情况下希望在内存中运行它,但物理文件也可以。
我能够通过更改 Illuminate\Foundation\Testing\DatabaseMigrations 得到我想要的;原文:
public function runDatabaseMigrations()
{
$this->artisan('migrate');
$this->app[Kernel::class]->setArtisan(null);
$this->beforeApplicationDestroyed(function () {
$this->artisan('migrate:rollback');
});
}
我的版本:
public function runDatabaseMigrations()
{
$this->artisan('migrate:refresh');
$this->artisan('db:seed');
$this->app[Kernel::class]->setArtisan(null);
$this->beforeApplicationDestroyed(function () {
$this->artisan('migrate:rollback');
});
}
但当然,我会在未来的一些更新中放弃这一点,所以我需要覆盖我的特性。
我将特征复制到 App\Traits\DatabaseMigrations.php 并更改了命名空间。
<?php
namespace App\Traits;
use Illuminate\Contracts\Console\Kernel;
trait DatabaseMigrations
{
/**
* Define hooks to migrate the database before and after each test.
*
* @return void
*/
public function runDatabaseMigrations()
{
$this->artisan('migrate:refresh');
$this->artisan('db:seed');
$this->app[Kernel::class]->setArtisan(null);
$this->beforeApplicationDestroyed(function () {
$this->artisan('migrate:rollback');
});
}
}
MyTest.php 如下:
<?php
namespace Tests\Browser;
use App\User;
use Tests\Browser\Pages\Dashboard;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
//use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\Traits\DatabaseMigrations;
class MyTest extends DuskTestCase
{
use DatabaseMigrations;
但这不起作用。我收到一个错误:PDOException: SQLSTATE[HY000]: General error: 1 no such table: users
所以不知何故,迁移不会在没有错误的情况下运行,但结果是我的测试失败了,因为没有表。
什么工作是这样的:
<?php
namespace Tests\Browser;
use App\User;
use Tests\Browser\Pages\Dashboard;
use Illuminate\Contracts\Console\Kernel;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
// use App\Traits\DatabaseMigrations;
class WorkshopRegistrationTest extends DuskTestCase
{
public function runDatabaseMigrations()
{
$this->artisan('migrate:refresh');
$this->artisan('db:seed');
$this->app[Kernel::class]->setArtisan(null);
$this->beforeApplicationDestroyed(function () {
$this->artisan('migrate:rollback');
});
}
use DatabaseMigrations;
但我不喜欢将该方法放入每个测试文件中。有谁知道为什么一种方法有效,而另一种方法无效?第一种方法在我看来,对OOP知之甚少,完全正常。