Skip to content

Instantly share code, notes, and snippets.

@jatubio
Last active August 29, 2015 14:21
Show Gist options
  • Save jatubio/09d4ca187aed91560a09 to your computer and use it in GitHub Desktop.
Save jatubio/09d4ca187aed91560a09 to your computer and use it in GitHub Desktop.
Laravel 5.1 - Using DatabaseTransactions with custom connections on Testing
<?php namespace JaTubio\Testing;
trait DatabaseTransactions {
protected function getConnectionName()
{
$model = $this->getModel();
if ( null !== $model )
{
return $model->getConnectionName();
}
return null;
}
/**
* @return \Portal\Entities\Model
*/
protected function getModel()
{
return null;
}
/**
* @before
*/
public function beginDatabaseTransaction()
{
$this->app->make('db')->setDefaultConnection($this->getConnectionName());
$this->app->make('db')->beginTransaction();
$this->beforeApplicationDestroyed(function ()
{
$this->app->make('db')->rollBack();
});
}
}
@jatubio
Copy link
Author

jatubio commented May 24, 2015

Use samples:

<?php

use JaTubio\Testing\DatabaseTransactions;

class ATestUsingDatabases extends TestCase {

    use DatabaseTransactions;

    protected function getModel()
    {
        return new App\Models\MyModel();
    }
}
<?php

use JaTubio\Testing\DatabaseTransactions;

class ATestUsingDatabases extends TestCase {

    use DatabaseTransactions;

    protected function getConnectionName()
    {
        return 'customconnection';
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment