Laravel Api TDD 附加用户

Laravel Api TDD attach users

我正在用 laravel 构建一个 API。如果会议用户存在,我想测试更新会议。这是我的控制器代码:

$title=$request->input('title');
        $description=$request->input('description');
        $user_id=$request->input('user_id');
    $meeting=new MeetingResource(Meeting::findOrFail($id));
          if(!$meeting->users()->where('users.id',$user_id)->first()){
                return response()->json(['msg'=>'users not registered for meeting,update not successfull'],401);
            }
              $meeting->title=$title;
            $meeting->description=$description;
            if(!$meeting->update()){
                return response()->json(['msg'=>'Error during updating'],404);
            }
            $response=[
                'msg'=>'meeting updated successfully',
                'meeting'=>$meeting
                ];
           return response()->json($response,201);  

这是我的测试

$meeting=new MeetingResource(factory(Meeting::class)->create());
        $user=factory(User::class)->create();
        $meeting->users()->attach($user);
        $this->assertTrue($meeting->users->contains($user));
        $meeting->load('users');
        $title="kola bola";
        $desc='lorem ipsum jipsum';
        $response=$this->patch("api/v1/meeting/{$meeting->id}",['title'=>$title,'description'=>$desc])
            ->assertStatus(201);

我收到 401 错误。

似乎您在调用 api 时未获得授权,Laravel 在测试场景中有一个用于授权用户的助手。

$response = $this->actingAs($user)
    ->patch("api/v1/meeting/{$meeting->id}",['title'=>$title,'description'=>$desc])
    ->assertStatus(201);