1

I'm writing some tests. Here is my test:

  /** @test */
  public function a_normal_user_cannot_access_the_admin_panel()
  {
    // Note: This is a regular user, not an admin
    $user = factory(User::class)->create();
    $this->actingAs($user);
    $this->visit('/admin');

    // ????
  }

In my MustBeAdministrator.php middleware:

  public function handle($request, Closure $next)
  {
      $user = $request->user();

      if ($user && $user->isAdmin) {
        return $next($request);
      }

      abort(403);
  }

When i visit /admin, the middleware aborts with a 403 error. How can i assert with phpunit that an http error was thrown? I know about $this->setExpectedException(), but i can't get it to work with http error. Am i doing this wrong?

NOTE: I'm very new to phpunit and also exceptions, so sorry if this is a stupid question. Here is the repo for this project if you need any other files, or you can just ask.

3
  • Hey, you can post an answer to your own question, it's not prohibited :) Commented Sep 27, 2016 at 5:14
  • @iScrE4m I did answer it, but SO won't let me accept it as an answer for 2 days :( I'll accept it then. Commented Sep 27, 2016 at 5:42
  • Oh sorry, I didn't notice, SO didn't show me in a review :) Commented Sep 27, 2016 at 5:43

2 Answers 2

1
$user = factory(User::class)->create();
$this->actingAs($user);
$this->setExpectedException('Symfony\Component\HttpKernel\Exception\HttpException');
$this->get('/admin');
throw $this->response->exception;

Found this article. Adding the setExpectedException line, the throw line, and changing visit to get seemed to solve my problem

Sign up to request clarification or add additional context in comments.

1 Comment

@MihkelAllorg SO won't let me accept it for another 2 hours. I will then.
0

if you want to get the full response object, you may use the call method

/** @test */
public function a_normal_user_cannot_access_the_admin_panel()
{
  // Note: This is a regular user, not an admin
  $user = factory(User::class)->create();
  $this->actingAs($user);
  $response = $this->call('GET', '/admin');

  $this->assert(403, $response->status());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.