Last active
July 10, 2020 02:57
-
-
Save agm1984/e3faf47ceeb24f97def2b63fbddd4fc2 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'; | |
/** | |
* 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::create([ | |
'name' => 'Test Admin', | |
'email' => '[email protected]', | |
'pasword' => bcrypt(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::create([ | |
'name' => 'Test User', | |
'email' => '[email protected]', | |
'password' => bcrypt(self::AUTH_PASSWORD), | |
]); | |
return $user; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example, in any unit test, you can call: