jgravois's avatar

Laravel 5.4 Testing Using Transactions -- Wrong Database

We have far too many migrations to use database migrations (because they really slow the testing down and then the developers don't test), so I am trying to move to use database transactions meaning moving from sqlite in :memory: to a sibling mysql database. However using the setup below, I am pulling from our production database rather than the new testing database.

#config/database.php

'mysql' => [
   'driver' => 'mysql',
   'host' => env('DB_HOST', '127.0.0.1'),
   'port' => env('DB_PORT', '3306'),
   'database' => env('DB_DATABASE', 'forge'),
   'username' => env('DB_USERNAME', 'root'),
   'password' => env('DB_PASSWORD', ''),
   'charset' => 'utf8mb4',
   'collation' => 'utf8mb4_unicode_ci',
   'prefix' => '',
   'strict' => true,
   'engine' => null,
 ],

 'mysql2' => [
     'driver' => 'mysql',
     'host' => env('DB2_HOST', '127.0.0.1'),
     'port' => env('DB2_PORT', '3306'),
     'database' => env('DB2_DATABASE', 'forge_test'),
     'username' => env('DB2_USERNAME', 'root'),
     'password' => env('DB2_PASSWORD', ''),
     'charset' => 'utf8mb4',
     'collation' => 'utf8mb4_unicode_ci',
     'prefix' => '',
     'strict' => true,
     'engine' => null,
  ],

#.env file

DB_CONNECTION=mysql
DB_HOST=--mask--
DB_PORT=3306
DB_DATABASE=--mask--
DB_USERNAME=--mask--
DB_PASSWORD=--mask--

#phpunit.xml

<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="mysql2"/>
<env name="DB_DATABASE" value="--mask--_test"/>

So to confirm, I modified the name field in the test database and ran this simple test

/** @test */
public function a_user_can_successfully_log_in()
{
        $this->disableExceptionHandling();
        $this->user = User::find(1);
        echo $this->user->name;

        $this->assertTrue(true);
}

and the output is definitely the version in the production DB

0 likes
2 replies
durino13's avatar

Did you solve this problem somehow? I have the same one ;-/

Please or to participate in this conversation.