php - How to Migrate and seed before the full test suite in Laravel with in memory database? -
i'm trying set test environment in laravel project. i'm using http://packalyst.com/packages/package/mayconbordin/l5-fixtures json seeding sqlite in memory database , calling:
artisan::call('migrate'); artisan::call('db:seed');
in setup function executed before every single test can grow thousands in project.
i tried setupbeforeclass didn't work. think there because createapplication method called in every test , reset whole application , wasn't loading fixtures json same reason.
this how did in case else struggling same, created base testclase
class inherits laravel's , did this:
/** * creates application. * * @return \illuminate\foundation\application */ public function createapplication() { return self::initialize(); } private static $configurationapp = null; public static function initialize(){ if(is_null(self::$configurationapp)){ $app = require __dir__.'/../bootstrap/app.php'; $app->loadenvironmentfrom('.env.testing'); $app->make(illuminate\contracts\console\kernel::class)->bootstrap(); if (config('database.default') == 'sqlite') { $db = app()->make('db'); $db->connection()->getpdo()->exec("pragma foreign_keys=1"); } artisan::call('migrate'); artisan::call('db:seed'); self::$configurationapp = $app; return $app; } return self::$configurationapp; } public function teardown() { if ($this->app) { foreach ($this->beforeapplicationdestroyedcallbacks $callback) { call_user_func($callback); } } $this->setuphasrun = false; if (property_exists($this, 'servervariables')) { $this->servervariables = []; } if (class_exists('mockery')) { mockery::close(); } $this->afterapplicationcreatedcallbacks = []; $this->beforeapplicationdestroyedcallbacks = []; }
i overwrote createapplication()
, teardown()
methods. changed first 1 use same $app
configuration , remove part of teardown()
flush $this->app
.
every other of test has inherit testclass , that's it.
everything else didn't work. works in memory database, it's 100s times faster.
if dealing user session, once log user in have log him out in tear down, otherwise user logged in because app environment never reconstructed or can dd refresh application every time want:
protected static $applicationrefreshed = false; /** * refresh application instance. * * @return void */ protected function forcerefreshapplication() { if (!is_null($this->app)) { $this->app->flush(); } $this->app = null; self::$configurationapp = null; self::$applicationrefreshed = true; parent::refreshapplication(); }
and add teardown()
before $this->setuphasrun = false;
:
if (self::$applicationrefreshed) { self::$applicationrefreshed = false; $this->app->flush(); $this->app = null; self::$configurationapp = null; }
Comments
Post a Comment