Summer Sale! All accounts are 50% off this week.

itachi's avatar

[TDD] assertDatabaseHas method when testing HTTP calls

Is it okay to add database assertions when using feature/functional testing?

Here I am trying to create user at /signup end point. In the Controller I am creating a user using User Model and returning the response values created from that model object. But I want to make sure the record is inserted in the database after signing up the user.

Can I use assertDatabaseHas here or I have to use it with factory methods only?

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

        $response = $this->postJson('/signup', [
            'name' => 'User',
            'email' => '[email protected]',
            'password' => 'password',
            'confirm_password' => 'password'
        ]);
        
        $response->assertStatus(HttpStatuses::HTTP_CREATED);
        $response->assertExactJson([
            'success' => false,
            'message' => 'User created successfully',
            'user' => [
                'name' => 'User',
                'email' => '[email protected]',
            ]
        ]);
        $this->assertDatabaseHas('users', [
            'email' => '[email protected]',
        ]);
    }
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

assertDatabaseHas is the appropriate assertion method to confirm a record is in the database.

A pre-action assertion might also be useful so you know that User record was created as a result of the request:

$this->assertDatabaseMissing('users', [
    'email' => '[email protected]',
]);
$response = $this->postJson('/signup', [
    //...
]);
// ...
$this->assertDatabaseHas('users', [
    'email' => '[email protected]',
]);
2 likes
itachi's avatar

Thanks for the response. I will add the other assertion too..

Please or to participate in this conversation.