0

I have created a testing database environment as follows:

return array(

    'default' => 'sqlite',

    'connections' => array(
        'sqlite' => array(
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => ''
        ),
    )
);

When I initialise my database in my setUp function this all appears to work fine:

Mail::pretend(true);
Artisan::call('migrate');

$this->seed();

Any query directly in my test directly in my test class returns what I would expect however if I call a function on my model that does anything with the database it uses my 'live' (I'm running this in a vagrant dev server so no risk of ruining anything) database instead of my test one. Do I need to change my configuration further to ensure it is using my test database? Or do I need to instantiate my model in a special way?

An example of what doesn't work. In my test:

// gets the correct company
$comp = Companies::find(1);
// gets results from wrong database
$comp->quotesAndOrders();

where quotesAndOrders does a simple query on a hasMany relationship (orders)

$this->orders()->get();
3
  • possible duplicate of Set SQLite as database for unit testing in Laravel 5.1 Commented Jul 7, 2015 at 23:40
  • This is Laravel 4, sorry. I thought I had put that but I had only put it in the tags. Updated the title to make it clearer Commented Jul 8, 2015 at 6:01
  • Oh in that case I have removed the duplicate vote, sorry about that Commented Jul 8, 2015 at 23:12

2 Answers 2

0

First of all on our .env file we have to add a new variable. looks like this.

DB_CONNECTION=sqlite

That's because of Laravel defaults to MySQL when this variable is absent from .env file:

see here..

'default' => env('DB_CONNECTION', 'mysql')

Now that our app is pointing into our sqlite database we can now run our migrations and seeding. After that if you just want to keep running MySQL remove DB_CONNECTION=sqlite from the .env file.

Now on your root folder you have a phpunit.xml file, open it and a new variable under <php> node

<env name="DB_CONNECTION" value="sqlite"/>
Sign up to request clarification or add additional context in comments.

1 Comment

This is laravel 4 sorry it wasn't clear. I have tried adding db connection to my .env.testing.php but it makes no difference
0

This project is based on someone elses code originally. In my companies model (annoyingly no other class and this was the first one I tested otherwise I would have spotted it sooner) there is an explicit definition to use the mysql database. I'm not sure why this was. I have removed that line and it now works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.