Last active
July 11, 2020 07:34
-
-
Save agm1984/7332c324165a020daa6ce6b91a437635 to your computer and use it in GitHub Desktop.
Quick demonstration of using `DatabaseTransactions` trait in Laravel unit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Feature; | |
use Illuminate\Foundation\Testing\DatabaseTransactions; | |
use Tests\TestCase; | |
class SomeTest extends TestCase | |
{ | |
use DatabaseTransactions; | |
// uncomment these if you want to use them, and mind the `: void` return type; | |
// in Laravel 5.7+, return type of void is mandatory (to enforce invariance~ of void) | |
/* public function setUp() : void | |
{ | |
parent::setUp(); | |
// maybe something here | |
}*/ | |
/* public function tearDown() : void | |
{ | |
parent::tearDown(); | |
// maybe something here | |
}*/ | |
/** @test */ | |
public function it_should_rename_someone_to_shirley() | |
{ | |
// do anything, such as: | |
$user = User::query()->firstWhere('email', '[email protected]'); | |
$user->name = 'Shirley Mutated'; | |
$user->save(); | |
$this->assertDatabaseHas('users', [ | |
'email' => '[email protected]', | |
'name' => 'Shirley Mutated', | |
]); | |
// as the unit test completes, the transaction will be rolled back, w0w!!1! | |
} | |
/** @test */ | |
public function it_should_still_be_named_shirley() | |
{ | |
// rely on unmutated data in the next test, such as: | |
$user = User::query()->firstWhere('email', '[email protected]'); | |
$this->assertDatabaseHas('users', [ | |
'email' => '[email protected]', | |
'name' => 'Shirley Immutable', | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This file exists alongside this other required setup file: https://gist.github.com/agm1984/38d893e801ff257cc5da567a42e29fee