I have a Laravel 4 test class with a number of tests for which I want to seed my database before running the tests. Using the setup() function to reseed for each test takes far too long. However, when I try seeding in the static setupBeforeClass() function or in the constructor, I obviously can't use the $this->seed() method.

But neither can I use programmatic Artisan commands, because when I do I get the following error: PHP Fatal error: Class 'Artisan' not found in <test class name>

Here is the code I'd like to use to seed:

Artisan::call('db:seed', array('--class'=>'TestSeeder');

Please let me know how I can seed my database once per test class rather than per test case

Question author Ralbatross | Source



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
        // ...more db init stuff, like seeding etc.

    public function setUp()

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

    // ...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...).

Answer author Neuronq

Ask about this question here!