miigaa's avatar
Level 24

Test Permissions?

I define my routes with a permission middleware like

Route::group(['middleware' => 'permission:manage_students'], function () {
    Route::resource('students', 'StudentsController');

    Route::put('students/{student}/password', 'StudentsController@changePassword');
});

Route::group(['middleware' => 'permission:manage_courses'], function () {
    //
});

How can i test it in unit test if routes requires correct permission? Please help me?

0 likes
3 replies
bobbybouwmann's avatar

You have two options here.

Run your tests without middleware. You can import this trade in your test to do that

use Illuminate\Foundation\Testing\WithoutMiddleware;

class SomeTest extends TestCase
{
    use WithoutMiddleware;

    // Do your tests here.
}

The other options needs a but more setup. You can for example create a user and simply set the correct permissions for that user. This however needs more setup for each tests, since each tests need different permissions according to the role of the user.

In general I would advise you to test your permissions in a separate test and use the WithoutMiddleware trait in your application tests ;)

miigaa's avatar
Level 24

Thank you! @bobbybouwmann. Do you have an example? I still don't get that.

Including permissions in my tests it doubles my testing code. like: if the user is admin, go next or if it is teacher or something stop the operation. Testing all those cases require so many tests. How can i avoid it?

bobbybouwmann's avatar

Like I said you can test is separately. Simple write a test for your permissions checker class. You can create a user with some permissions and then simply check if they can visit a given route or perform a given post request. You should get a 403 request back from the server, since the user doesn't have the rights to visit that.

1 like

Please or to participate in this conversation.