I am trying to run my unit test and create a database during setup. For some reason I am getting the error Unknown database 'coretest'
. If I create the database though manually and run the test then I get Can't create database 'coretest'; database exists
.
The drop database statement works just now the create database.
Here is my setUP and tearDown methods:
class TestCase extends Illuminate\Foundation\Testing\TestCase {
/**
* Default preparation for each test
*/
public function setUp() {
parent::setUp();
DB::statement('create database coretest;');
Artisan::call('migrate');
$this->seed();
Mail::pretend(true);
}
public function tearDown() {
parent::tearDown();
DB::statement('drop database coretest;');
}
}
In Laravel 5 it's possible to call migrations internally to the Laravel process which ends up running a good bit quicker than using external commands.
In TestCase::setUp (or earlier), call the migration command with:
I feel like I have a much cleaner way of doing this. Just execute the commands normally through the shell.
The reason why you get this error is simply because laravel tries to connect to database specified in config, which doesn't exist.
The solution is to build your own PDO connection from the settings without specifying database (PDO allows this) and run
CREATE DATABASE $dbname
statement using it.We used this approach for testing in our project without any problem.
Here some code:
neoascetic has the best answer because essentially you have to boot laravel's database config file again.
So, a clever hack is to create database again after you have dropped it. No need to touch config/database.