Laravel在测试时创建数据库 [英] Laravel create database when testing

查看:151
本文介绍了Laravel在测试时创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行我的单元测试,并在设置过程中创建数据库.由于某种原因,我收到错误Unknown database 'coretest'.如果我手动创建数据库并运行测试,则会得到Can't create database 'coretest'; database exists.

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.

drop database语句现在可以在创建数据库中使用.

The drop database statement works just now the create database.

这是我的setUP和tearDown方法:

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;');
    }
}

推荐答案

出现此错误的原因仅是因为laravel尝试连接到config中指定的数据库,该数据库不存在.

The reason why you get this error is simply because laravel tries to connect to database specified in config, which doesn't exist.

解决方案是从设置中构建您自己的PDO连接而不指定数据库(PDO允许这样做),并使用它运行CREATE DATABASE $dbname语句.

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.

此处一些代码:

<?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}:user={$username} password={$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

这篇关于Laravel在测试时创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆