Tzo*_*Noy 0 php sqlite phpunit laravel eloquent
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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");
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
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';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3117 次 |
| 最近记录: |