1

I have the following test file in my Laravel application:

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ApiAuthControllerTest extends TestCase{

    use DatabaseTransactions;

    public function testLogin(){

        // Test login success
        $response = $this->json('POST', '/login', array(
            'email' => 'hello@yahoo.com',
            'password' => 'sometext'
        ))->decodeResponseJson();
        return $response['token'];

    }

   /**
     * @depends testLogin
     */
    public function testLogout($token){

        // Test logout success
        $this->json('DELETE', '/logout', array(
            'token' => $token
        ))->assertReponseStatus(200);

    }

}

I am using the DatabaseTransactions class to wrap my tests as transactions so they don't write to my database. I noticed that using this class will wrap every individual test within my class as a transaction.

I would like to wrap the entire class as a transaction. In my example above, I need for the token that was generated from my login request to be persistent in the database as I test the logout request.

How would I do this with Laravel?

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248

1 Answers1

2

Unfortunately, I don't believe this is possible. Laravel refreshes the app instance on setUp/tearDown. In PHPUnit, these functions are run every test method. Thus, using transactions means there will be no persistence between test methods.

You can, however, generate the token again in your testLogout test. Since your logout test relies on a token to be present, there is nothing inherently wrong with that approach.

samrap
  • 5,595
  • 5
  • 31
  • 56