Last active
September 9, 2020 14:06
-
-
Save neoascetic/6504409 to your computer and use it in GitHub Desktop.
[Laravel] Bootstrap file for (re)creating database before running tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Bootstrap file for (re)creating database before running tests | |
* | |
* You only need to put this file in "bootstrap" directory of the project | |
* and change "bootstrap" phpunit parameter within "phpunit.xml" | |
* from "bootstrap/autoload.php" to "bootstap/testing.php" | |
*/ | |
$testEnvironment = 'testing'; | |
$config = require("app/config/{$testEnvironment}/database.php"); | |
extract($config['connections'][$config['default']]); | |
$connection = new PDO("{$driver}:host={$host}", $username, $password); | |
$connection->query("DROP DATABASE IF EXISTS ".$database); | |
$connection->query("CREATE DATABASE ".$database); | |
require_once('app/libraries/helpers.php'); | |
// run migrations for packages | |
foreach(glob('vendor/*/*', GLOB_ONLYDIR) as $package) { | |
$packageName = substr($package, 7); // drop "vendor" prefix | |
passthru("./artisan migrate --package={$packageName} --env={$testEnvironment}"); | |
} | |
passthru('./artisan migrate --env='.$testEnvironment); | |
require('autoload.php'); // run laravel's original bootstap file |
@mpyw nice solution!
not working @mpyw solution, simplier same solution in setUp function call same thing Artisan::call('migrate:fresh')
and it shouldn't work also
because initial solution creates database instead of modifying existing db
I created command, thats can create database by passed db name (if not exists). And then call this command every time in setUp method .
more simpler using this piece of code in setUp method
// Get the default connection name, and the database name for that connection from laravel config.
$connectionName = config('database.default');
$databaseName = config("database.connections.{$connectionName}.database");
// Set the database name to null so DB commands connect to raw mysql, not a database.
config(["database.connections.{$connectionName}.database" => null]);
// Create the db if it doesn't exist.
DB::statement("CREATE DATABASE IF NOT EXISTS " . $databaseName);
// Reset database name and purge database-less connection from cache.
config(["database.connections.{$connectionName}.database" => $databaseName ]);
DB::purge();
source laravel/framework#19412 (comment)
You can't use RefreshDatabase trait in first initial test. Because this trait (and some others) should use database that could be not exists
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Best solution for PHP 7.1 + Laravel 5.5
phpunit.xml
tests/bootstrap.php