Skip to content

Instantly share code, notes, and snippets.

@agm1984
Created July 10, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agm1984/6804d4a2032f856991423d59749e4460 to your computer and use it in GitHub Desktop.
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);`
<?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