简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM