Skip to content
Guest
Laravel · Course Syllabus Show lessons
Production Laravel · 8 min read · Intermediate

Feature Testing with RefreshDatabase

Write fast automated HTTP and database tests that catch regressions before you ever deploy.

What you'll learn

  • Use `RefreshDatabase` to isolate every test run cleanly
  • Simulate logged-in requests with `$this->actingAs($user)`
  • Assert both HTTP status codes and database state with `assertDatabaseHas`

Overview

Write fast automated HTTP and database tests that catch regressions before you ever deploy.

Code Example

<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('authenticated users can create a study note', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)->postJson('/api/notes', [
        'title' => 'Eloquent Eager Loading',
        'body' => 'Always use with() to avoid N+1 queries.',
    ]);

    $response->assertCreated();
    $this->assertDatabaseHas('notes', ['user_id' => $user->id]);
});

Key Takeaways

  • Use RefreshDatabase to isolate every test run cleanly
  • Simulate logged-in requests with $this->actingAs($user)
  • Assert both HTTP status codes and database state with assertDatabaseHas

Quick Check

Check Your Understanding

Score: 0 / 1

1. What does `$this->actingAs($user)` do inside a Laravel feature test?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind