PaulClarke's avatar

Null object in test using Eloquent

So I am attempting to test that when a user has forgotten their password, they can enter their email address and receive a password reset email.

The code works, but the test fails. (I have made a create helper method like JW had on the 'How to Build a Forum' series).

 /** @test */
    public function a_user_can_request_an_email_to_reset_their_password()
    {
        Notification::fake();

        $user = create(User::class, [
            'email' => '[email protected]',
        ]);

        dd($user);  //This correctly shows the full User object

        dd(User::findByEmail('[email protected]')); //This is null ! 

        $this->post('/password/reset', ['email' => '[email protected]'])
                ->assertStatus(302)
                ->assertSessionHas('success', 'Email sent, please check your inbox.');

        Notification::assertSentTo($user, NotifyPasswordReset::class);
    }

I am using Database Migrations and an Sqlite DB. But I thought that only reset per test, not mid-test. Cannot anyone suggest which I have done wrong please?

0 likes
3 replies
shez1983's avatar

the problem is that findByEmail() doesnt exist.. u have to use a where clause ( idid a quick search on my laravel 5.5 and couldnt find this function, unless you have written it yourself?)

PaulClarke's avatar

@shez1983 Eloquent automatically allows for ‘findBy’ + attribute name is my understanding (the code works in production). But even using

User::where(‘email’, ‘[email protected]’)->

works in the controller, but not in the test.

PaulClarke's avatar
PaulClarke
OP
Best Answer
Level 24

@shez1983 Thanks for your idea - I have solved it now! And am somewhat embarrassed. The reason it was not finding the user was that in my User Factory I have an active attribute which was set to false and then on my User Model I have a global scope which removes anyone whose active status is false. Doh. My bad.

Please or to participate in this conversation.