Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active July 11, 2020 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agm1984/7332c324165a020daa6ce6b91a437635 to your computer and use it in GitHub Desktop.
Save agm1984/7332c324165a020daa6ce6b91a437635 to your computer and use it in GitHub Desktop.
Quick demonstration of using `DatabaseTransactions` trait in Laravel unit tests
<?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', 'shirley@asample.com');
$user->name = 'Shirley Mutated';
$user->save();
$this->assertDatabaseHas('users', [
'email' => 'shirley@asample.com',
'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', 'shirley@asample.com');
$this->assertDatabaseHas('users', [
'email' => 'shirley@asample.com',
'name' => 'Shirley Immutable',
]);
}
}
@agm1984
Copy link
Author

agm1984 commented Jul 10, 2020

This file exists alongside this other required setup file: https://gist.github.com/agm1984/38d893e801ff257cc5da567a42e29fee

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment