mercredi 28 août 2019

Authorise a user with Laravel Passport when testing RESTful controllers update method

Every time I run the test, I'm getting a 403 response status, what am I doing wrong in here? I have tried to remove Passport authorization from the test, but then I'm getting a redirect to a login page, 302 status response.

//PostTest:

public function test_can_update_post()
{
    //creating a user
    $user = factory(User::class)->create();

    //creating an author for post
    $author = factory(Author::class)->create([
        'user_id' => $user->id,
    ]);

    //creating a post
    $post = factory(Post::class)->create([
        'author_id' => $author->id,
    ]);

    $data = [
        'title' => $this->faker->title,
        'content' => $this->faker->paragraph,
    ];

    //authorizing user
    //I have tried to remove this line, then I'm gettig a redirect to login page 302
    $user = Passport::actingAs($user, ['posts/' . $post->id]);

    $this->actingAs($user)
        ->patch(route('posts.update', $post->id), $data)
        ->assertStatus(200);// why I'm getting 403???
}

//API route:

Route::patch('posts/{post}')
    ->uses('PostController@update')
    ->middleware('auth:api')
    ->name('posts.update');


//PostController update method:

public function update(PostUpdateRequest $request, Post $post)
{
    $this->authorize('update', $post);

    $post->title = $request->input('title');
    $post->content = $request->input('content');

    $post->save();

    return new PostResource($post);
}

//PostPolocy

public function update(User $user, Post $post)
{
    return Author::where('user_id', $user->id)->first()->id === $post->author_id;
}

I expect response status 200



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire