kfirba's avatar
Level 50

How to test middleware

Hello!

I'm trying to limit the access to my application for registered users only. I'm also restricting the registration form to registered users only. I need to somehow test that it is actually working. I'm trying to figure out how I can possible write such a test while focusing on the Domain layer, which means I can't do something like

$this->visit('/');

I need to somehow send a call to that route and make sure that it doesn't allow not registered users to access it (Will redirect to auth/login).

0 likes
5 replies
JarekTkaczyk's avatar

I suppose you mean Behat, right?

This little piece is enough:

      Scenario: Guest redirect to login page
        Given I am on "/"
         Then I should be on "/auth/login"
kfirba's avatar
Level 50

@JarekTkaczyk This syntax is tightly coupling me with the UI. I've written a more general scenario and I have no problem testing it through the UI layer, but I'm trying to figure a way I can test it through the Domain layer, which means I can't assume browser at-all.

JarekTkaczyk's avatar

@kfirba You are talking about the middlewares, that are part of the HTTP layer of your application - by definition it assumes browser-like solution. It doesn't need to be browser, but HTTP request, so Mink should do.

kfirba's avatar
Level 50

@JarekTkaczyk I see. You got a point there.

Another question, when I want to check that a u user is logged in, e.g. Given I am logged in, does it suffice to do something like this for Domain layer tests:

Auth::attempt($credentials);
JarekTkaczyk's avatar

@kfirba Consider these examples:

    /**
     * @Given I am logged in as :email with :password
     */
    public function iAmLoggedInAs($email, $password)
    {
        $this->visit('login');
        $this->fillField('email', $email);
        $this->fillField('password', $password);
        $this->pressButton('Sign in');
    }

    /**
     * @Given I am logged in as an admin
     */
    public function iAmLoggedInAsAnAdmin()
    {
        $this->thereIsUser(['role' => 'admin', 'email' => 'admin@domain.com', 'password' => 'secret']);

        $this->visit('login');
        $this->fillField('email', 'admin@domain.com');
        $this->fillField('password', 'secret');
        $this->pressButton('Sign in');
    }

I prefer to rely on the UI, since I'm testing the UI. That said I don't use code-only login, because it could end with not having login form at all ;)

Please or to participate in this conversation.