Created
September 10, 2014 04:43
-
-
Save colindecarlo/27e5f7d5261d285df460 to your computer and use it in GitHub Desktop.
Jordan Eldredge (@captbaritone) wrote a really helpful post about "Speeding up Laravel tests with database transactions" (http://jordaneldredge.com/blog/speed-up-laravel-tests-with-database-transactions), you should read it. I took what he had done and expanded on it a little, this is my implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
As Jordan did, I changed the phpunit bootstrap file from 'bootstrap/autoload.php' to 'bootstrap/testing.php'. My version differs only in that I reference an environment variable `PHPUNIT_SEED_DB`, if that variable is present then I seed the database. | |
// bootstrap/testing.php | |
<?php | |
$shouldSeed = getenv('PHPUNIT_SEED_DB'); | |
if ($shouldSeed) { | |
passthru("php artisan --env='testing' migrate:refresh"); | |
passthru("php artisan --env='testing' db:seed --class=TestDatabaseSeeder"); | |
} | |
require __DIR__ . '/autoload.php'; | |
Doing this allows me to run the migrations on demand instead of *all the time*; helpful when I want to run a single test (or suite of tests) that don't require a database. You can set the environment variable at the time you run phpunit so it's set only for that process, kinda like flashing. | |
$ PHPUNIT_SEED_DB=true ./phpunit | |
Since I may or may not be running the migrations, I needed to conditionally start and rollback the database transactions. I modified TestCase.php, which ships with Laravel, to do this. | |
// tests/TestCase.php | |
<?php | |
abstract class TestCase extends Illuminate\Foundation\Testing\TestCase { | |
protected static $withMigrations; | |
public static function setUpBeforeClass() | |
{ | |
parent::setUpBeforeClass(); | |
static::$withMigrations = getenv('PHPUNIT_SEED_DB'); | |
} | |
public function setUp() | |
{ | |
parent::setUp(); | |
if (static::$withMigrations) { | |
DB::beginTransaction(); | |
} | |
} | |
public function tearDown() | |
{ | |
if (static::$withMigrations) { | |
DB::rollBack(); | |
} | |
parent::tearDown(); | |
} | |
// the rest | |
Thats it. Thanks again to Jordan for writing the post, I was tearing out what's left of my hair trying to do this on my own before I found it. Now my tests run quite a bit faster. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment