如何在 Laravel 5.8 中测试当前密码的有效性

How to test validation of current password in Laravel 5.8

我正在尝试测试当前密码是否与数据库中的相同。

我的简化控制器:

class ChangePasswordController extends Controller
{
    public function update(Request $request, User $user)
    {
        $this->validate($request, [
            'current_password' => ['required', new CurrentPassword()],
            'password' => 'required|string|min:6|confirmed'
        ]);

        $user->update([
            'password' => bcrypt($request->password)
        ]);

    }
}

在我的自定义 CurrentPassword 规则中,我正在检查这样的哈希值:

class CurrentPassword implements Rule
{

    public function passes($attribute, $value)
    {
        $check = Hash::check($value, auth()->user()->password);
        dump($check);
        return $check;
    }


    public function message()
    {
        return 'Current password is incorrect.';
    }
}

我对自定义规则的测试是:

/** @test */
public function an_authenticated_user_may_change_own_password()
{
    $this->withoutExceptionHandling();

    $user = factory(User::class)->create([
        'password' => '1234'
    ]);

    $this->actingAs($user)->patch("/profile/{$user->id}/password", [
        'current_password' => '1234',
        'password' => 'mynewpassword',
        'password_confirmation' => 'mynewpassword'
    ]);

    $this->assertTrue(Hash::check('mynewpassword', $user->fresh()->password));
}    

不幸的是我遇到了一个错误:

1) Tests\Feature\UpdatePasswordTest::an_authenticated_user_may_change_own_password Illuminate\Validation\ValidationException: The given data was invalid.

我不明白为什么会这样。当我 运行 这个测试时,我的 dump($check); returns 是错误的。我的 $value 是“1234”,auth()->user()->password returns 也是“1234”。也许有人知道我做错了什么。

此测试正在变绿:

 /** @test */
    public function current_password_must_be_valid()
    {
        $user = factory(User::class)->create([
            'password' => '1234'
        ]);

        $this->actingAs($user)->patch("/profile/{$user->id}/password", [
            'current_password' => '12345',
            'password' => 'mynewpassword',
            'password_confirmation' => 'mynewpassword'
        ])->assertSessionHasErrors('current_password');

    }

你也应该在你的工厂中散列你的密码,否则 Eloquent 将以明文形式存储它(这就是为什么 auth()->user()->password returns '1234')

public function current_password_must_be_valid()
{
    $user = factory(User::class)->create([
        'password' => Hash::make('1234'); // remember to import the Hash facade
    ]);

    ...
}