Ronster's avatar

setting right database for test

Hi,

I use the model connection attribute in all my models since i'm working with multiple databases/schema's. I'm at a point where I need to write tests and this is where I'm struggling with at the moment.

At the moment I set the DB_Connection through the models constructor. I named it "SHARED_CONNECTION"

public function __construct()
    {
        Parent::__construct();

        $this->setConnection(
            env('SHARED_CONNECTION')
        );
    }

In the browser this works like expected and my app functions as expected. Now, when writing tests, I get a lot of errors. first of all I have updated the phpunit.xml file with the "SHARED_CONNECTION" env variable and set it to a sqlite database (in memory later).

<env name="SHARED_CONNECTION" value="shared_testing"/>

I'm using faker to generate an account and a user.

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
        'account_id' => function () {
            return factory(App\Account::class)->create()->id;
        }
    ];
});

when running the tests we now get the following error: PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: accounts.name when setting the $connection property directly the account is being inserted.

So it looks like the constructor is not being called of something when running tests.

What is the best way to handle this?

0 likes
0 replies

Please or to participate in this conversation.