Mark Karavan
Mark Karavan

Reputation: 2674

Laravel 5.3 DatabaseMigrations are destructive

Laravel 5.3 with mysql, PHPUnit 5.7.4

When I create a test in PHPUnit with use DatabaseMigrations;, it destroys the data that it queries.

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ThingsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function there_are_more_than_1000_things()
    {
        $things = App\Thing::all();

        $this->assertGreaterThan(1000, count($things));
    }

Before I run phpunit, there are lots of things. After running it, mysql says ERROR 1146 (42S02): Table 'database.things' doesn't exist

Any ideas how to stop this?

Upvotes: 1

Views: 355

Answers (2)

Leonid Shumakov
Leonid Shumakov

Reputation: 1319

DatabaseMigrations is a trait and it execs:

  1. before test 'php artisan migrate' // creates your tables, but doesn't seed them
  2. after test 'php artisan migrate:rollback' // remove tables

So, 1st - make sure you're using another database for testing.

2nd - seed with fake data your tables before testing your Things class.

Alternative: use DatabaseTransactions trait instead of DatabaseMigrations. In that case each test activity will be wrapped in a database transaction. After test all your changes will be dropped by transaction's rollback automatically.

Upvotes: 2

1000Nettles
1000Nettles

Reputation: 2334

You can be using a test database with PHPUnit within your Laravel application. Right now your tests are using your main database and will modify existing information.

Please see https://stackoverflow.com/a/35228697/823549 for how to do this.

Upvotes: 1

Related Questions