Skip to content

Instantly share code, notes, and snippets.

@agm1984
Last active Jul 10, 2020
Embed
What would you like to do?
Demonstrates how to use a "select or create" pattern for Laravel unit testing via `$this->actingAs($user);`
<?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', 'test-admin@example.com');
if ($user) {
return $user;
}
$user = User::create([
'name' => 'Test Admin',
'email' => 'test-admin@example.com',
'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', 'test-user@example.com');
if ($user) {
return $user;
}
$user = User::create([
'name' => 'Test User',
'email' => 'test-user@example.com',
'password' => bcrypt(self::AUTH_PASSWORD),
]);
return $user;
}
}
@agm1984
Copy link
Author

agm1984 commented Jul 10, 2020

For example, in any unit test, you can call:

$this->actingAs($this->adminUser);

// and

$this->actingAs($this->user);

Loading

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