Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active Jul 11, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@agm1984 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