jeudi 25 juin 2015

Laravel Mock Facade shouldReceive Not Working As Intended

This test fails because it will never pass the Auth::attempt() function call. I put a dd() statement to prove that it won't make it.

If I remove the two Auth::shouldReceive() calls the code will run the first dd() statement.

If I keep even one Auth::shouldReceive() calls the first dd() statement will never get called.

I must be something silly that I'm not getting because I've looked over many tutorials.

Controller

public function postLogin() {
    $email = Input::get('email');
    $password = Input::get('password');
    dd('Does not make it to this line with auth::shouldReceive() in the test');
    if (Auth::attempt(array('email'=>$email, 'password'=>$password))) {
        dd("Doesn't make it here either with auth::shouldReceive() mock.");
        $user = Auth::user();
        Session::put('user_timezone', $user->user_timezone);
        return Redirect::to('user/dashboard')->with('message', 'You are now logged in!');
    } else {
        return Redirect::to('user/login')->with('message', 'Your username/password combination was incorrect')->withInput();
    }
}

Test

public function testUserTimezoneSessionVariableIsSetAfterLogin()
{
    $user = new User();
    $user->user_timezone = 'America/New_York';
    $user->email = 'test@test.com';
    $user->password = 'test';

    $formData = [
        'email' => 'test@test.com',
        'password' => '123',
    ];

    \Auth::shouldReceive('attempt')->once()->with($formData)->andReturn(true);
    \Auth::shouldReceive('user')->once()->andReturn($user);

    $response = $this->call('POST', '/user/login', $formData);
    $this->assertResponseStatus($response->getStatusCode());


    $this->assertSessionHas('user_timezone');
}

Aucun commentaire:

Enregistrer un commentaire