Laravel 附加多对多关系时测试中断

Laravel test breaks on attaching many-to-many relationship

我有一个测试应该测试默认用户的注册。测试函数如下所示:

   public function testCanRegister()
    {
        $this->json('POST', '/register', [
            'name' => 'John Doe',
            'email' => 'johndoe@hotmail.com',
            'password' => bcrypt('1234')
        ])
            ->assertStatus(200)
            ->assertJsonFragment([
                'id' => 3,
                'name' => 'John Doe',
                'email' => 'johndoe@hotmail.com'
            ]);
    }

它给我以下错误:

Expected status code 200 but received 500. Failed asserting that 200 is identical to 500.

正在测试的功能是这样的:

   public function register(RegisterRequest $request)
    {
        $validatedData = $request->validated();

        $user = new User;
        $user->name = $validatedData['name'];
        $user->email = $validatedData['email'];
        $user->password = bcrypt($validatedData['password']);
        $user->roles->attach(1); // give User role.

        if (!$user->save()) {
            return response()->json('Gebruiker kan niet worden geregistreerd', 500);
        }

        // Create session for the just registered User.
        Auth::attempt([
            'email' => $user->email,
            'password' => $request->json('password')
        ]);

        return response()->json($user, 200);
    }

当我评论这行时:

$user->roles->attach(1);

测试成功。关于如何改进我的测试以使其成功的任何想法?唯一不起作用的是附加角色。

喜欢many to many relation doc

$user = App\User::find(1);

$user->roles()->attach($roleId);

所以,当您附加时,您附加的是关系,而不是集合... 请注意 $user->roles 是角色的集合,而 $user->roles() 是一个关系....

只需将您的声明更新为:

$用户->角色()->附加(1);

试试 $user->roles()->attach(1);先保存用户后。

喜欢:

$用户->保存();

$用户->角色()->附加(1);