secmuhammed
3 months ago

how to mock update eloquent method

Posted 3 months ago by secmuhammed

Hello There, I've been trying to mock the eloquent update method while testing that a user can actually change his/her password, I tried to mock it, partially mock it and then I get inside the method and die and dump the output, always returns me a false, I'm not hitting the database, but once I change the passed user from being a new instance using factory make to a factory create, It returns true, so is there any work around to make it work out without touching database?

my code for changing user password.

    public function handle($data = []) {
        if ($this->changePassword($data)) {
            return new GenericPayload([
                'message' => 'Password has been changed successfully !',
            ]);
        }
        return new GenericPayload([
            'message' => 'Uhmmm, Could not change your password',
        ], 406);
    }
    protected function changePassword($data)
    {
        if (\Hash::check($data['current_password'], auth()->user()->password)) {
            return auth()->user()->update([
                'password' => bcrypt($data['password'])
            ]);
        }

    }


unit-test

    /** @test */
    public function it_should_let_user_change_password_if_given_current_password_is_correct()
    {
        $user = factory(User::class)->make([
            'password' => 'hello'
        ]);
        $mock = \Mockery::mock('\App\Users\Domain\Models\User[update]');
        $mock->shouldReceive('update')->with([
            'password' => 'secret'
        ])->once();

        Auth::shouldReceive('user')->times(2)->andReturn($user);
        Hash::shouldReceive('check')->once()->andReturn(true);
        Hash::makePartial();
        
        $changeUserPasswordService = new ChangeUserPasswordService;

        $response = $changeUserPasswordService->handle([
            'current_password' => $user->password,
            'password' => 'secret'
        ]);
        $this->assertEquals(200, $response->getStatus());

    }

Please sign in or create an account to participate in this conversation.