mardi 28 mars 2017

Test that middleware was used in Laravel

I have a post route inside a middleware that checks whether a user performing a request belongs to a specific role. I have 4 roles in total. And I have found it silly to write tests like:

  • testRole2CanNotDoAction
  • testRole3CanNotDoAction
  • testRole4CanNotDoAction

every time I want to test some action. So it would be really nice if I can just write 1 test

  • testMiddlewareWasCalled

to assure that route is placed in right place. How can I do it? To give you the context lets assume I have the following middleware:

class MustBeRole1
{
    public function handle($request, Closure $next)
    {
        $user = $request->user();
        if ($user && $user->isRole1()) {
            return $next($request);
        }

        abort(403, 'You are not an role1!');
    }
}

and following routes:

Route::group(['middleware' => ['isRole1']], function () {
    Route::post('/testAction', ['as' => 'testAction', 'uses' => 'testActionController@test']);
}

How should my test look like?

Aucun commentaire:

Enregistrer un commentaire