I
I
ildar-meyker2021-02-13 16:17:29
Laravel
ildar-meyker, 2021-02-13 16:17:29

Question about the RefreshDatabase trait, the setUp method of the test class, and seeds. How does it work?

Apparently, I did not fully understand the order of running the tests.

I have env.testing which refers to the test db. Model factories are created, DatabaseSeeder.php uses these factories and successfully creates data. That is, when you run php artisan db:seed --env=testing everything is OK.

TestCase.php looks like this. The RefreshDatabase trait is used, the protected $seed = true property is defined ; and overridden setUp() method.

I figured it works like this. When starting each test (class), the setUp() method is called firstthis class, which cleans tables, runs migrations, and populates a test table with seeds using DatabaseSeeder.php. Then in my case 2 more users are created.

And now, after running all the tests, I look into the test database and do not see these 2 users. Actually, why?

<?php

namespace Tests;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use App\Models\User;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use RefreshDatabase;

    protected $seed = true;
    protected $admin;
    protected $user;
    protected $unverifiedUser;

    protected function setUp(): void
    {
        parent::setUp();

        $this->admin = User::find(1);

        $this->user = User::factory()->create();

        $this->unverifiedUser = User::factory()->create([
            'email_verified_at' => null
        ]);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2021-02-13
@Nc_Soft

It is written in the documentation that RefreshDatabase cleans the database after each test
https://laravel.com/docs/8.x/database-testing#rese...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question