How to rollback transactions when doing functional testing with Symfony2

You could use a dedication test database for testing

Another option is using Codeception. This is a unit testing bundle that works with Symfony. If you use this, you can configure it to use a test database and then "clean it up" after each testing cycle.
An example yaml configuartion to do that would be something like, it is the cleanup: true that does what you want;

class_name: UnitTester
modules:
    enabled:
        - Asserts
        - Symfony2:
            app_path: '../../app'
            var_path: '../../app'
            environment: 'test'
        - Doctrine2:
            depends: Symfony2
            cleanup: true
        - \AppBundle\Helper\Unit

I would recommend to use this bundle: https://packagist.org/packages/dama/doctrine-test-bundle

Its very easy to setup and will roll-back any database changes automatically after every single testcase. No need to implement any custom things.


Are you doing more than one request with the Client? If so, you problem might be that the client shutdowns the kernel after one request was performed. But you can disable that with $this->client->disableReboot() So this snippet snippet should be idempotent:

public function setUp()
{
    $this->client = $this->createClient(['environment' => 'test']);
    $this->client->disableReboot();
    $this->em = $this->client->getContainer()->get('doctrine.orm.entity_manager');
    $this->em->beginTransaction();
}

public function tearDown()
{
    $this->em->rollback();
}

public function testCreateNewEntity()
{
    $this->client->request('GET', '/create/entity/form');
    $this->client->request('POST', '/create/entity/unique/123');
}