How Do I Seed My Database in the setupBeforeClass Method in a Laravel 4 Unit Test?

An "improvised" but pretty clean imho way to achieve a similar effect would be to do this in setUp, but have it run only once (similar to what setupBeforeClass does) like this:

use Illuminate\Support\Facades\Artisan;

class ExampleTest extends TestCase {

    protected static $db_inited = false;

    protected static function initDB()
    {
        echo "\n---initDB---\n"; // proof it only runs once per test TestCase class
        Artisan::call('migrate');
        // ...more db init stuff, like seeding etc.
    }

    public function setUp()
    {
        parent::setUp();

        if (!static::$db_inited) {
            static::$db_inited = true;
            static::initDB();
        }
    }

    // ...tests go here...
}

...this is my solution and it seems simple enough and works fine, solving the performance problems of seeding and rebuilding the db structure before every test run. But remember, the "right" way to do testing, that gives you the greatest confidence your tests methods don't get subtly interdependent in bug-hiding ways, is to re-seed your db before every test method, so just put seeding code in plain setUp if you can afford the performance penalty (for my test cases, I couldn't afford it, but ymmv...).


I had the same problem and solved with this

passthru('cd ' . __DIR__ . '/../.. & php artisan migrate:refresh & db:seed --class=TestSeeder');

This is so far the best solution I found

class ExampleTest extends TestCase {
/**
 * This method is called before
 * any test of TestCase class executed
 * @return void
 */
public static function setUpBeforeClass()
{
    parent::setUpBeforeClass();
    print "\nSETTING UP DATABASE\n";
    shell_exec('php artisan migrate --seed');
}

/**
 * This method is called after
 * all tests of TestCase class executed
 * @return void
 */
public static function tearDownAfterClass()
{
    shell_exec('php artisan migrate:reset');
    print "\nDESTROYED DATABASE\n";
    parent::tearDownAfterClass();
}
/** tests goes here **/ }