In my experience, the process of migrating the testing database is the one that takes the most of the time and also consumes most of my system's resources.
My scenario includes a long and complex database (which comprises multiple schemas and tables) that needs to be migrated in order to perform my tests. Disabling php-xdebug extension didn't help so much since the bottleneck is the database migrations ()
What I do, in order to speed up my test suite is the following:
-
I stop using DatabaseMigrations trait, since it forces my database to be refreshed each time I run a test.
-
I migrate my testing database once before making any test (the testing database will contain all necessary tables without data)
php artisan migrate:refresh
- I created a custom
clearDatabases method within Tests\TestCase as follows:
/**
* Truncates all tables of given connections.
* @param array $connections
*/
protected function clearDatabases(array $connections): void
{
foreach ($connections as $connection) {
$tables = DB::connection($connection)->getDoctrineSchemaManager()->listTableNames();
DB::connection($connection)->statement('SET FOREIGN_KEY_CHECKS=0');
foreach ($tables as $table) {
if ('migrations' == $table) {
continue;
}
DB::connection($connection)->table($table)->truncate();
}
DB::connection($connection)->statement('SET FOREIGN_KEY_CHECKS=1');
}
}
The method accepts an array of the connections as an argument. Each connection corresponds to a different mysql schema. The method finds all tables related to that connection and truncates their data.
- I explicitly call
clearDatabases from my test'ssetUp method by passing the required connections ($schemas) required for this particular test
class ApplicationFooTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$this->clearDatabases([DB_CONNECTION_FOO')]);
}
}
That is, before running each of my tests, I use the database that I have already migrated and clear any data
The advantages of the proposed solution is that I was able to dramatically improve the time needed for my test suite to run by aprox -96%
The main disadvantage is that I have to manually refresh my testing database each time I add a new migrations (still, this is not a big problem for me, since adding new migrations is something that I don't do all the time when testing )