Skip to content

Instantly share code, notes, and snippets.

@agm1984
Created 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';
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', 'test-admin@example.com');
if ($user) {
return $user;
}
$user = User::generate('Test Admin', 'test-admin@example.com', 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::generate('Test User', 'test-user@example.com', self::AUTH_PASSWORD);
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment