Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 687
Kbir Mhrjn Avatar asked Jan 07 '14 03:01

Kbir Mhrjn


1 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

like image 187
lauri108 Avatar answered Nov 15 '22 00:11

lauri108