zeshan77's avatar

How to assert if a middleware is applied on a specific route

I have a case where I need to set default locale on certain routes in my applications. So I created a middleware that does this job perfectly fine if it is applied on a route. While creating tests I need to assert whether certain routes has applied this middleware or not. Is there a way in laravel where we can do this?

My middleware

class ForceBackOfficeLocale
{
    public function handle($request, Closure $next)
    {
        if (! in_array(App::currentLocale(), Locales::enabledInBackOffice())) {
            App::setLocale(Locales::default());
        }

        return $next($request);
    }
}

Thanks in advance.

0 likes
3 replies
SilenceBringer's avatar

@zeshan77 something like

  1. App::setLocale with locale which is in Locales::enabledInBackOffice()
  2. do request to route with the given middleware
  3. check App::currentLocale() is the same as you set in step 1

and second check

  1. App::setLocale with locale which is not in Locales::enabledInBackOffice()
  2. do request to route with the given middleware
  3. check App::currentLocale() equals to Locales::default()

or test middleware directly https://semaphoreci.com/community/tutorials/testing-middleware-in-laravel-with-phpunit

zeshan77's avatar

Thanks @silencebringer for the help!

I am already doing what you just mentioned, my question is how do I test if a route applies a specific middleware or not (not if middleware works or not).

Regards,

SilenceBringer's avatar

@zeshan77 try

$middlewares = \Route::getCurrentRoute()->middleware();

and check your middleware is in the list

Please or to participate in this conversation.