在测试 RESTful 控制器更新方法时使用 Laravel Passport 授权用户
Authorise a user with Laravel Passport when testing RESTful controllers update method
每次我 运行 测试时,我都会收到 403 响应状态,我在这里做错了什么?
我试图从测试中删除 Passport 授权,但随后我收到了重定向到登录页面的 302 状态响应。
//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);
$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;
}
我希望响应状态为 200
我已将 PostPolicy 更新方法中的行更改为:
if(!$user->author) {
return false;
}
return $user->author->id == $post->author_id;
这对我有用。
每次我 运行 测试时,我都会收到 403 响应状态,我在这里做错了什么? 我试图从测试中删除 Passport 授权,但随后我收到了重定向到登录页面的 302 状态响应。
//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);
$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;
}
我希望响应状态为 200
我已将 PostPolicy 更新方法中的行更改为:
if(!$user->author) {
return false;
}
return $user->author->id == $post->author_id;
这对我有用。