Home » Php » php – Testing in Laravel, setUp & tearDown doesn't rollBack my database transaction?

php – Testing in Laravel, setUp & tearDown doesn't rollBack my database transaction?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m having this weired behaviour in Laravel testing. Let me show you my tests.

<?php 
class MatchesControllerTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        DB::beginTransaction();
    }

    public function tearDown()
    {
        DB::rollBack();

    }

     public function testForFun()
    {
             $title = 'Yay Great Post';
        // "Create" post
        Post::create(compact('title'));
             $crawler = $this->client->request('GET', 'posts');

        $this->assertEquals(
            1,
            count($crawler->filter("body:contains('{$title}')")),
            "Expected to see the text '{$title}' within a body element."
        );
    }
}

Now ideally, the test should create a row and delete as soon as the test ends but its not happening, is there something else I should have done. I know the rollback is called when some unexpected exception has occured but I’m deliberately calling it at the end, won’t this should work as we think it should?

How to&Answers:

At least in Laravel 5, you can add the DatabaseMigrations trait:

use Illuminate\Foundation\Testing\DatabaseMigrations;

class MatchesControllerTest extends TestCase {
    use DatabaseMigrations;

    public function testForFun() { 
       // your test.. 
    }
}

That trait creates and removes the database tables you’ve defined in your migrations just for your test. More on that trait in the Laravel testing documentation