Ошибка при тестировании PHPUnit Laravel - SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "users" does not exist
Хочу написать простой HTTP тест, суть которого просто проверить работоспособность открытия нужной страницы. На сайте предусмотрены разные права (админы и пользователи), поэтому есть необходимость аутентифицировать конкретного пользователя как текущего.
Вот код теста:
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class CommonUserBaseHttpTest extends TestCase
{
protected User $user;
protected function setUp(): void
{
parent::setUp();
$this->user = User::factory()->common()->create();
}
protected function tearDown(): void
{
$this->user->delete();
parent::tearDown();
}
public function test_dashboard()
{
$response = $this->actingAs($this->user)->get('/dashboard/forms');
$response->assertStatus(200);
}
}
При запуске выдает такую ошибку:
• Tests\Feature\CommonUserBaseHttpTest > dashboard
Illuminate\Database\QueryException
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "users" does not exist
LINE 1: insert into "users" ("name", "email", "email_verified_at", "...
^ (SQL: insert into "users" ("name", "email", "email_verified_at", "password", "remember_token", "role", "updated_at", "created_at") values (test, test, 2022-09-23 12:07:51, $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi, PDwo8NdF3L, 1, 2022-09-23 12:07:51, 2022-09-23 12:07:51) returning "id")
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:742
738▕ // If an exception occurs when attempting to run a query, we'll format the error
739▕ // message to include the bindings with SQL, which will make this exception a
740▕ // lot more helpful to the developer instead of just the database's errors.
741▕ catch (Exception $e) {
➜ 742▕ throw new QueryException(
743▕ $query, $this->prepareBindings($bindings), $e
744▕ );
745▕ }
746▕ }
+16 vendor frames
17 tests/Feature/CommonUserBaseHttpTest.php:17
Illuminate\Database\Eloquent\Factories\Factory::create()
В интернете советуют менять PHPUnit\Framework\TestCase на Tests\TestCase и добавлять parent::setUp(), но всё это у меня уже есть.
Ради интереса пробовал писать сырой sql запрос вида DB:raw('SELECT * FROM users') в тесте, на это он не ругался.
Структура папки tests:
- tests
-
- Feature
-
-
- CommonUserBaseHttpTest.php
-
-
-
- ExampleTest.php
-
-
- Unit
-
-
- ExampleTest.php
-
- CreatesApplication.php
- TestCase.php
Ответы (1 шт):
Зашёл в phpunit.xml и в строке <env name="DB_DATABASE" value="testing"/> значение testing поменял на название своей базы данных. Починилося.