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
RefreshDatabaseto 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.