Why are you making the Role and it's Permissions in-memory only? Have you tried actually creating the database records?
Laravel Testings - All api calls 403 error.
I've got an application that i've started writing tests for. The auth was generated with Laravel UI, but the dashboard you get to is written in VUE.js. So i've needed to use the API.
I'm creating some tests but everytime i try to do this i get a 403 error for unauthorized. The only thing i can think of is something is missing from my request headers. Its worth noting that all the routes work correctly on the frontend and trying to access them via the api route shows the correct response with logged in or not/or has the correct permissions.
My api.php
Route::middleware('auth')->group(function () {
Route::apiResource('users', UserController::class);
Route::apiResource('roles', RoleController::class);
Route::apiResource('permission-groups', PermissionGroupController::class);
Route::apiResource('customers', CustomerController::class);
Route::apiResource('packages', PackageController::class);
Route::apiResource('projects', ProjectController::class);
// Tasks
Route::apiResource('tasks', TaskController::class);
Route::patch('tasks/{task}/completed', [TaskController::class, 'complete'])->name('task.complete');
Route::patch('tasks/{task}/order', [TaskController::class, 'order']);
Route::apiResource('/tasks/{task}/notes', NoteController::class, ['except' => ['index', 'show', 'update']]);
Route::patch('/tasks/{task}/status', [TaskController::class, 'status']);
});
My test case that fails -
class ExampleTest extends TestCase
{
use RefreshDatabase;
/**
* Test the api returns customers
*
* @test
* @return void
*/
public function api_gets_customers(): void
{
$this->login();
$response = $this->getJson('api/customers');
$response->assertStatus(200);
}
The login function from testCase that the test extends. Its woth noting that all the permissions and roles are correct on the user from acting as
protected function login(array $states = null)
{
$factory = User::factory();
$this->actingAs($this->actor = $factory->create(), 'web');
if (!$this->actor->roles->count()) {
$this->actor->setRelation('roles', collect([
(new Role(['name' => 'Test Role']))->setRelation('permissions', Permission::all())
]));
}
return $this;
}
Is there something that i'm doing wrong to the login part that requires something extra to access the API?
@ashler2 the variable in the test is not the Authenticated User in the Request. Just store the Role and Permissions so they are in the database to be queried whenever the Test Request is made.
Please or to participate in this conversation.