Laravel Feature Testing: HTTP Tests and Database Assertions

Laravel Feature Testing: HTTP Tests and Database Assertions

Feature tests in Laravel sit between unit tests and end-to-end tests. They test your application through its HTTP layer — making requests and asserting on responses — without a real browser. They're the most useful category of tests for most Laravel applications because they exercise your routes, controllers, middleware, validation, and database together.

This post covers the full feature testing toolkit: HTTP helpers, response assertions, and database state verification.

Setting Up a Feature Test

Laravel generates feature tests in tests/Feature/. Create one with:

php artisan make:test UserRegistrationTest

This produces a class extending Tests\TestCase, which itself extends Laravel's Illuminate\Foundation\Testing\TestCase. That base class bootstraps the application and gives you access to all the HTTP testing helpers.

<?php

namespace Tests\Feature;

use Tests\TestCase;

class UserRegistrationTest extends TestCase
{
    public function test_user_can_register_with_valid_data(): void
    {
        $response = $this->postJson('/api/register', [
            'name' => 'Jane Doe',
            'email' => 'jane@example.com',
            'password' => 'secret1234',
            'password_confirmation' => 'secret1234',
        ]);

        $response->assertStatus(201);
    }
}

HTTP Test Helpers

Laravel provides helpers for every HTTP verb:

$this->get('/dashboard');
$this->post('/users', $data);
$this->put('/users/1', $data);
$this->patch('/users/1', ['name' => 'Updated']);
$this->delete('/users/1');

// JSON variants (set Accept and Content-Type headers automatically)
$this->getJson('/api/users');
$this->postJson('/api/users', $data);
$this->putJson('/api/users/1', $data);
$this->patchJson('/api/users/1', $data);
$this->deleteJson('/api/users/1');

The Json variants also automatically decode the response body, so response assertions against JSON work without manual decoding.

You can pass additional headers as a third argument:

$this->getJson('/api/users', ['X-Custom-Header' => 'value']);

Response Assertions

Every test call returns a TestResponse object with a rich assertion API.

Status codes:

$response->assertStatus(200);
$response->assertOk();           // 200
$response->assertCreated();      // 201
$response->assertNoContent();    // 204
$response->assertNotFound();     // 404
$response->assertUnauthorized(); // 401
$response->assertForbidden();    // 403
$response->assertUnprocessable(); // 422

JSON assertions:

$response->assertJson(['name' => 'Jane']);  // partial match

$response->assertJsonFragment(['email' => 'jane@example.com']);

$response->assertJsonStructure([
    'data' => [
        '*' => ['id', 'name', 'email', 'created_at'],
    ],
    'meta' => ['total', 'per_page', 'current_page'],
]);

$response->assertJsonPath('data.0.name', 'Jane Doe');
$response->assertJsonCount(10, 'data');
$response->assertJsonMissing(['password']);

assertJson does a partial match — the response can contain additional keys. assertExactJson requires an exact match of the full JSON body.

View and redirect assertions:

$response->assertViewIs('users.index');
$response->assertViewHas('users');
$response->assertViewHasAll(['users', 'filters']);

$response->assertRedirect('/login');
$response->assertRedirectToRoute('dashboard');

Session and cookie assertions:

$response->assertSessionHas('success', 'Profile updated.');
$response->assertSessionHasErrors(['email']);
$response->assertSessionHasErrors(['email' => 'The email is invalid.']);
$response->assertCookie('preferences');

Database Assertions

After making a request, you often want to verify that the database changed as expected.

public function test_registration_persists_user(): void
{
    $this->postJson('/api/register', [
        'name' => 'Jane Doe',
        'email' => 'jane@example.com',
        'password' => 'secret1234',
        'password_confirmation' => 'secret1234',
    ])->assertCreated();

    $this->assertDatabaseHas('users', [
        'name' => 'Jane Doe',
        'email' => 'jane@example.com',
    ]);
}

public function test_deletion_removes_record(): void
{
    $user = User::factory()->create();

    $this->actingAs($user)
         ->deleteJson("/api/users/{$user->id}")
         ->assertNoContent();

    $this->assertDatabaseMissing('users', ['id' => $user->id]);
    $this->assertSoftDeleted('users', ['id' => $user->id]); // if using SoftDeletes
}

assertDatabaseCount verifies the total number of rows matching a condition:

$this->assertDatabaseCount('users', 1);
$this->assertDatabaseCount('orders', 0);

Managing Database State: RefreshDatabase vs DatabaseTransactions

Two traits handle test isolation:

RefreshDatabase runs migrations fresh at the start of the test suite and wraps each test in a transaction that rolls back afterward. If your migrations have never run, it runs them. If they have, it resets the database.

use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    public function test_creates_user(): void
    {
        User::factory()->create(['email' => 'a@example.com']);
        $this->assertDatabaseCount('users', 1);
    }
}

DatabaseTransactions wraps each test in a transaction and rolls it back after. It's faster than RefreshDatabase because it doesn't re-run migrations, but it requires the database to already be in a clean state and won't work correctly with tests that use multiple database connections or queue jobs that run in separate processes.

use Illuminate\Foundation\Testing\DatabaseTransactions;

class OrderTest extends TestCase
{
    use DatabaseTransactions;
}

For most projects, RefreshDatabase is the safer default. The speed difference only becomes noticeable at large test suite sizes.

Acting As a User

Most feature tests need authentication. Laravel provides actingAs():

public function test_authenticated_user_sees_dashboard(): void
{
    $user = User::factory()->create();

    $this->actingAs($user)
         ->get('/dashboard')
         ->assertOk()
         ->assertViewIs('dashboard');
}

For API tests with specific guards:

$this->actingAs($user, 'api')
     ->getJson('/api/profile')
     ->assertOk();

You can also set up auth state once in setUp() if all tests in a class require the same authenticated user:

protected User $user;

protected function setUp(): void
{
    parent::setUp();
    $this->user = User::factory()->create();
    $this->actingAs($this->user);
}

Testing Validation

Feature tests are the right place to verify that your validation rules reject bad input:

public function test_registration_requires_email(): void
{
    $this->postJson('/api/register', [
        'name' => 'Jane',
        'password' => 'secret1234',
        'password_confirmation' => 'secret1234',
    ])->assertUnprocessable()
      ->assertJsonValidationErrors(['email']);
}

public function test_registration_rejects_duplicate_email(): void
{
    User::factory()->create(['email' => 'jane@example.com']);

    $this->postJson('/api/register', [
        'name' => 'Jane',
        'email' => 'jane@example.com',
        'password' => 'secret1234',
        'password_confirmation' => 'secret1234',
    ])->assertUnprocessable()
      ->assertJsonValidationErrors(['email']);
}

assertJsonValidationErrors checks that the response contains a 422 with validation errors for the specified fields.

Faking External Services

Feature tests should be fast and deterministic. Anything that hits an external service needs to be faked.

use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Http;

public function test_registration_sends_welcome_email(): void
{
    Mail::fake();

    $this->postJson('/api/register', [
        'name' => 'Jane',
        'email' => 'jane@example.com',
        'password' => 'secret1234',
        'password_confirmation' => 'secret1234',
    ])->assertCreated();

    Mail::assertSent(WelcomeEmail::class, fn ($mail) =>
        $mail->hasTo('jane@example.com')
    );
}

public function test_order_dispatches_fulfillment_job(): void
{
    Queue::fake();

    $this->actingAs($this->user)
         ->postJson('/api/orders', ['product_id' => 1, 'quantity' => 2])
         ->assertCreated();

    Queue::assertPushed(FulfillOrder::class, fn ($job) =>
        $job->quantity === 2
    );
}

Http::fake() intercepts outbound HTTP calls:

Http::fake([
    'stripe.com/*' => Http::response(['id' => 'ch_test'], 200),
    'api.sendgrid.com/*' => Http::response([], 202),
]);

Full Example: Testing a Resource Endpoint

Putting it all together — a complete test class for a REST resource:

<?php

namespace Tests\Feature;

use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PostControllerTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();
        $this->user = User::factory()->create();
    }

    public function test_lists_all_posts(): void
    {
        Post::factory()->count(5)->create();

        $this->actingAs($this->user)
             ->getJson('/api/posts')
             ->assertOk()
             ->assertJsonCount(5, 'data')
             ->assertJsonStructure(['data' => [['id', 'title', 'body']], 'meta']);
    }

    public function test_creates_post(): void
    {
        $this->actingAs($this->user)
             ->postJson('/api/posts', [
                 'title' => 'Hello World',
                 'body' => 'First post content',
             ])
             ->assertCreated()
             ->assertJsonPath('data.title', 'Hello World');

        $this->assertDatabaseHas('posts', ['title' => 'Hello World']);
    }

    public function test_unauthenticated_request_is_rejected(): void
    {
        $this->getJson('/api/posts')->assertUnauthorized();
    }

    public function test_cannot_update_another_users_post(): void
    {
        $post = Post::factory()->create(); // different user

        $this->actingAs($this->user)
             ->putJson("/api/posts/{$post->id}", ['title' => 'Stolen'])
             ->assertForbidden();
    }
}

This covers the happy path, authentication, authorization, and validation in about 40 lines. Feature tests at this level give you high confidence that your HTTP layer is working correctly.

For production monitoring beyond your test suite, HelpMeTest runs continuous end-to-end checks against your live application — catching regressions between deployments that CI alone won't catch.

Read more

Start now free