T
T
Tokenchik2020-03-07 17:26:16
PHPUnit
Tokenchik, 2020-03-07 17:26:16

How to include test data for each test when developing a package?

Hello everyone, there is a package that needs to be covered with tests. In each test, a trait is connected to connect the path of migrations and seeders.

trait Setup {

    use WithLoadMigrationsFrom;

    protected $connectionsToTransact = ['testing'];

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

        $this->loadMigrationsFrom(realpath(__DIR__ . '/../database/migrations'));
        $this->registerSeedsFrom(__DIR__ . '/../database/seeds');
        $this->artisan('migrate', [
            '--path' => realpath(__DIR__ . '/../database/migrations'),
            '--realpath' => true,
            '--database' => 'testing'
        ]);
        $this->artisan('db:seed --class=DatabaseSeeder', []);
    }

    /**
     * Register seeds.
     *
     * @param  string  $path
     * @return void
     */
    protected function registerSeedsFrom($path)
    {
        foreach (glob("$path/*.php") as $filename)
        {
            include $filename;
            $classes = get_declared_classes();
            $class = end($classes);

            $command = Request::server('argv', null);
            if (is_array($command)) {
                $command = implode(' ', $command);
                if ($command == "artisan db:seed") {
                    Artisan::call('db:seed', ['--class' => $class]);
                }
            }

        }
    }

    protected function tearDown(): void
    {
        Artisan::call('migrate:reset');
        parent::tearDown();
    }
}


As a result, now there are two test files, when I run the tests I get an error
Fatal error: Cannot declare class DatabaseSeeder, because the name is already in use


Of course, the error clearly states that I already have the DatabaseSeeder class. How to solve this problem?
Let me remind you that this is done so that when you run the tests, you can see the seeders and migrations inside the package.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question