5

I feel confused about how to setup a database for the test envrionment in symfony 4. I used to deal with it in config_test.yml file in symfony 3 and below.

What is the best practice ? Should I recreate a doctrine.yaml file in config/packages/test ?

The documentation mentions how to run functional test using a database by editing the phpunit config :

<phpunit>
    <php>
        <!-- the value is the Doctrine connection string in DSN format -->
        <env name="DATABASE_URL" value="mysql://USERNAME:PASSWORD@127.0.0.1/DB_NAME" />
    </php>
    <!-- ... -->
</phpunit>

However it does not feet my needs since I need to be able to update schema/load fixtures to the test env.

Ousmane
  • 2,261
  • 2
  • 22
  • 34

1 Answers1

7

For what you want to do I usually create a custom test bootstrap that runs the required doctrine commands and looks something like this:

# tests/bootstrap.php
<?php

if (isset($_ENV['BOOTSTRAP_RESET_DATABASE']) && $_ENV['BOOTSTRAP_RESET_DATABASE'] == true) {
    echo "Resetting test database...";
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:schema:drop --env=test --force --no-interaction',
        __DIR__
    ));
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:schema:update --env=test --force --no-interaction',
        __DIR__
    ));
    passthru(sprintf(
        'php "%s/../bin/console" doctrine:fixtures:load --env=test --no-interaction',
        __DIR__
    ));
    echo " Done" . PHP_EOL . PHP_EOL;
}
require __DIR__.'/../vendor/autoload.php';

In my phpunit.xml.dist I addd the env variable:

<env name="DATABASE_URL" value="sqlite:///%kernel.project_dir%/var/test.db"/>
<env name="BOOTSTRAP_RESET_DATABASE" value="1" />

If you want to see a basic example I have a Symfony 4 demo project that uses this to set up a basic test database that is used by Functional Tests using the web test case. You can find it on GitHub: dbrumann/product-api

dbrumann
  • 15,087
  • 1
  • 35
  • 52
  • I tried something like that, but it seems the passthu'ed console command does not run the the environment defined by my ` – olidem Oct 23 '19 at 07:53
  • 1
    There is a hierarchy which values are being used, so it could be that your project's `.env.test(.local)` file or your system environment overwrites the settings from the `phpunit.xml.dist`. – dbrumann Oct 23 '19 at 09:39
  • Ah, no I just found out that it is impossible to define ` – olidem Oct 23 '19 at 09:41