Created
July 10, 2020 02:51
-
-
Save agm1984/6804d4a2032f856991423d59749e4460 to your computer and use it in GitHub Desktop.
Demonstrates how to use a "select or create" pattern for Laravel unit testing via `$this->actingAs($user);`
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; | |
use App\User; | |
use Illuminate\Foundation\Testing\DatabaseTransactions; | |
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; | |
use Spatie\Permission\Models\Role; | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication, DatabaseTransactions; | |
const AUTH_PASSWORD = 'password'; | |
public function setUp() : void | |
{ | |
parent::setUp(); | |
} | |
public function tearDown() : void | |
{ | |
parent::tearDown(); | |
} | |
/** | |
* Creates and/or returns the designated admin user for unit testing | |
* | |
* @return \App\User | |
*/ | |
public function adminUser() : User | |
{ | |
$user = User::query()->firstWhere('email', '[email protected]'); | |
if ($user) { | |
return $user; | |
} | |
$user = User::generate('Test Admin', '[email protected]', self::AUTH_PASSWORD); | |
$user->assignRole(Role::findByName('admin')); | |
return $user; | |
} | |
/** | |
* Creates and/or returns the designated regular user for unit testing | |
* | |
* @return \App\User | |
*/ | |
public function user() : User | |
{ | |
$user = User::query()->firstWhere('email', '[email protected]'); | |
if ($user) { | |
return $user; | |
} | |
$user = User::generate('Test User', '[email protected]', self::AUTH_PASSWORD); | |
return $user; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment