lundi 11 mars 2019

How can I use both PHPUnit dependency feature and Laravel WithTransactions trait?

In Laravel, there's a trait called DatabaseTransactions which rolls back all transactions made by a test, to keep the database clean and isolated. It's fine and useful.

But there's a feature in PHPUnit called Test Dependencies in which you can use another test's output:

/**
 * @test
 */
public function a_producer_test()
{
    $user = factory(User::class)->create();

    return $user;
}

/**
 * @test
 * @depends a_producer_test
 */
public function a_consumer_test(User $user)
{
    $id = $user->id;
}

When using DatabaseTransactions, you cannot use $user inside a_consumer_test because the transaction that created the user is rolled back and thus $user is empty. If you remove use DatabaseTransactions; from the test class, everything works fine and you can use $user.

Now I want to have $user inside my a_consumer_test method, yet I want to roll back transactions and clean my database after execution of the tests. How can I do that?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire