I have a package that uses DB, and I wanted to create some tests that will run with sqlite in memory for the tests.
Now I have this base test class:
use Illuminate\Database\Capsule\Manager;
class TestCaseDb extends \PHPUnit_Framework_TestCase {
protected $db;
protected $tbmsg;
public function setUp()
{
parent::setUp(); // //DONT CARE
League\FactoryMuffin\Facade::getFaker()->unique($reset = true);//DONT CARE
$this->initDb();
$this->initTbmsg(); //DONT CARE
}
protected function initDb() {
//confi gfor the sqlite
$capsule = new Manager();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$this->db = $capsule->getDatabaseManager();
//loading simple DB tables creation
$importSql = file_get_contents(__DIR__.'/dumps/dump.sql');
$this->db->statement($importSql);
}
}
Now as you can see here I create the sqlite database and create the eloquent DB object for handling it.
But, now if I query it with the
$this->db->select("whatever");
it works great.
But when I try to use an Eloquent object so it will tell me that the specific table doesn't exist. (It exists 100% in the first Db)
So I think that eloquent model tries to connect to another DB connection and not for the one I created.
IE - this is the test that gives the error:
class SimpleTest extends TestCaseDb {
/**
* @test
*/
public function first() {
//the below row works!
//$this->db->insert('insert into conv_users (conv_id, user_id) values (?, ?)', array(1, 2));
//the insert with Eloquent fails....
$data = League\FactoryMuffin\Facade::create('Tzookb\TBMsg\Models\Eloquent\Conversation', []);
$this->assertTrue(true);
}
}
You can see the code in my github package as well: (branch dev) https://github.com/tzookb/tbmsg/tree/dev/tests
What you are doing is unnecessary.
Laravel provides you with tools out of the box to do what you are trying to do already.
Add this in your setUp()
of TestCase
.
Artisan::call('migrate');
$this->seed();
It will migrate your migrations in your SQLite memory database.
You should have something like this then:
<?php
class TestCase extends \Illuminate\Foundation\Testing\TestCase {
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
$this->seed();
}
/**
* Creates the application.
*
* @return \Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__.'/../../bootstrap/start.php';
}
}