gpt4 book ai didi

php - 一般错误 : 1 no such table: users in Laravel Unit Test

转载 作者:行者123 更新时间:2023-12-04 11:51:10 24 4
gpt4 key购买 nike

我创建了以下单元测试:

    <?php

namespace Tests\Unit;

use Tests\TestCase;
use App\User;
use App\Organization;

class UserTest extends TestCase
{
public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);

$this->assertContains($organization, $user->owned_organizations);
}
}

当我运行它时,我得到:
SQLSTATE[HY000]: General error: 1 no such table: users

然而,当我打开 php artisan tinker :
>>> factory(App\User::class)->create()
=> App\User {#3048
name: "Margret Armstrong",
email: "shanel.cormier@example.net",
email_verified_at: "2020-05-18 01:22:30",
updated_at: "2020-05-18 01:22:30",
created_at: "2020-05-18 01:22:30",
id: 1,
}

很明显,工厂在工作, table 存在。

这里发生了什么?

谢谢,

最佳答案

当您以一种或另一种方式运行测试时,您将需要迁移数据库。

一种常见的方法是利用 RefreshDatabase特征。

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\User;
use App\Organization;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
use RefreshDatabase;

public function testUserHasOwnedOrganization()
{
$user = factory(User::class)->create();
$organization = factory(Organization::class)->create([
'organizer_id' => $user->id,
]);

$this->assertContains($organization, $user->owned_organizations);
}
}

看看能不能帮到你。

您可以在此处找到有关它的更多信息:
https://laravel.com/docs/7.x/database-testing

关于php - 一般错误 : 1 no such table: users in Laravel Unit Test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61861047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com