elo's avatar
Level 3

Laravel PHPUnit Test Forbidden Error

I have written two PHPUnit test that updates and deletes a book record only if the user is authenticated. I am using Passport for authentication but my test fails with a 403 error for both test. What could be wrong with my code below

public function test_onlyAuthenticatedUserCanUpdateBookSuccessfully()
    {
        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $book = factory(Book::class)->create();

        $response = $this->json('PUT', '/api/books/'.$book->id, [
                'id'    => $book->id,
                'title' => 'Updated book title',
                'author'=> 'New Guy'
            ]);

        $response->assertStatus(201);
    }

public function test_onlyAuthenticatedUserCanDeleteBook()
    {
        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $book = factory(Book::class)->create();

        $response = $this->json('DELETE', '/api/books/'.$book->id);

        $response->assertStatus(204);
    }
0 likes
2 replies
tykus's avatar

Try instead:

 $response = $this->actingAs($user, 'api')->json('DELETE', '/api/books/'.$book->id);
1 like

Please or to participate in this conversation.