Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 67 ยท Testing

HTTP and Database Tests

Test Laravel routes and the database - get() and post() helpers, assertStatus, assertJson, RefreshDatabase, factories, actingAs and assertDatabaseHas.

The most valuable Laravel tests act like a user: they send a request to your application and check what comes back and what changed in the database. Laravel makes this easy. Inside a Feature test you call $this->get('/posts') or $this->post('/posts', [...]), and the framework runs your routes, middleware and controllers in memory, without a real web server and without a network.

This lesson covers the HTTP test helpers, assertions on responses and JSON, resetting the database between tests, creating data with factories, logging in a user with actingAs(), and checking the database. The Laravel code is read-only. The runnable example builds a miniature app and test client over SQLite so you can see the same flow with your own eyes. Make sure you know the basics from Testing with Pest.

Sending requests in a test

Every HTTP verb has a helper that returns a test response:

PHP
test('the posts page loads', function () {
    $response = $this->get('/posts');

    $response->assertOk();
});

test('a post can be created', function () {
    $response = $this->post('/posts', [
        'title' => 'Hello',
        'body'  => 'First post',
    ]);

    $response->assertRedirect('/posts');
});

For APIs there are JSON versions, which send Accept: application/json and encode the body for you:

PHP
$this->getJson('/api/posts');
$this->postJson('/api/posts', ['title' => 'Hello']);
$this->putJson('/api/posts/1', ['title' => 'Changed']);
$this->deleteJson('/api/posts/1');

Nothing is sent over the network. Laravel builds a Request object, runs it through the HTTP kernel, and hands you the Response. That is why feature tests are fast enough to run hundreds of times.

sequenceDiagram
    participant T as Test
    participant K as HTTP kernel
    participant A as Your route and controller
    participant D as Database
    T->>K: $this->post("/posts", data)
    K->>A: middleware, then controller
    A->>D: insert row
    A-->>K: redirect response
    K-->>T: TestResponse
    T->>T: assertRedirect(), assertDatabaseHas()

The test calls the kernel directly, then asserts on the response and on the database.

Response assertions

The TestResponse object has dozens of assertions. The common ones:

PHP
$response->assertStatus(201);
$response->assertOk();                       // 200
$response->assertCreated();                  // 201
$response->assertNoContent();                // 204
$response->assertNotFound();                 // 404
$response->assertForbidden();                // 403
$response->assertRedirect('/login');
$response->assertSee('Hello');               // HTML contains text (escaped)
$response->assertSeeText('Hello');
$response->assertDontSee('Secret');
$response->assertViewIs('posts.index');
$response->assertViewHas('posts');
$response->assertSessionHasErrors(['title']);

For JSON, assertJson() checks that the response contains a fragment, and assertJsonPath() reads a dotted path:

PHP
$this->getJson('/api/posts/1')
    ->assertOk()
    ->assertJson(['data' => ['title' => 'Hello']])
    ->assertJsonPath('data.author.name', 'Ada')
    ->assertJsonCount(3, 'data.comments');

assertJsonStructure() checks the shape without caring about values, which is useful for API contracts:

PHP
->assertJsonStructure(['data' => ['id', 'title', 'created_at']]);

Keeping tests independent: RefreshDatabase

Each test must start from the same known state, otherwise tests pass or fail depending on the order they run in. In a Feature test, add the RefreshDatabase trait, usually once in tests/Pest.php:

PHP
pest()->extend(Tests\TestCase::class)
    ->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
    ->in('Feature');

RefreshDatabase runs your migrations once, then wraps every test in a database transaction that is rolled back when the test ends. You get a clean database for each test at almost no cost. Laravel's default phpunit.xml points the test environment at a fast in-memory SQLite database (this project does the same), so tests never touch your development data.

Never run tests against your real development or production database. Check phpunit.xml (or .env.testing) sets DB_CONNECTION to a test database before you write your first destructive test.

Creating data with factories

Instead of building rows by hand, use model factories:

PHP
$user = User::factory()->create();
$posts = Post::factory()->count(3)->for($user)->create();
$draft = Post::factory()->create(['published_at' => null]);

$made = Post::factory()->make();   // in memory, not saved

create() inserts a row; make() only builds the object. Pass an array to override attributes that matter to the test, and leave the rest random. That makes the test say what is important: "a post with no publish date", not twenty irrelevant fields.

Acting as a logged-in user

Many routes require authentication. actingAs() signs a user in for the request without going through the login form:

PHP
test('a guest cannot create a post', function () {
    $this->post('/posts', ['title' => 'Hi'])
        ->assertRedirect('/login');
});

test('a user can create a post', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->post('/posts', ['title' => 'Hi', 'body' => 'Text'])
        ->assertRedirect('/posts');

    $this->assertDatabaseHas('posts', [
        'title'   => 'Hi',
        'user_id' => $user->id,
    ]);
});

For API routes protected by Sanctum, use Sanctum::actingAs($user, ['posts:write']). Always test both sides of a rule: the allowed user and the guest or wrong user. Authorization bugs hide in the missing negative test.

Database assertions

These check the database directly, so a redirect that "looked right" is not enough:

PHP
$this->assertDatabaseHas('posts', ['title' => 'Hi']);
$this->assertDatabaseMissing('posts', ['title' => 'Old']);
$this->assertDatabaseCount('posts', 3);
$this->assertModelExists($post);
$this->assertModelMissing($post);
$this->assertSoftDeleted($post);

Validation failures deserve tests too, and they should also prove nothing was saved:

PHP
test('a title is required', function () {
    $this->actingAs(User::factory()->create())
        ->post('/posts', ['title' => '', 'body' => 'Text'])
        ->assertSessionHasErrors('title');

    $this->assertDatabaseCount('posts', 0);
});

A miniature app and test client

You cannot boot Laravel here, so this example builds a tiny stand-in: an in-memory SQLite database, a two-route app, a test client with post() and actingAs(), and the assertions assertStatus and assertDatabaseHas. The names mimic Laravel, but the code is ours, not the framework's.

PHP A mini feature test over SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice freshDatabase() at the start of every scenario. That is the job RefreshDatabase does for you, with a rolled-back transaction instead of dropping tables. Each scenario also tests one rule and checks the database afterwards, which is the habit to copy.

Practical habits

  • Test behavior, not implementation. Assert on the response and the database, not on which private method ran.
  • Arrange only what matters. Override just the attributes the test depends on.
  • Test failure paths. Guests, wrong users, invalid input and missing records.
  • Use $this->withoutExceptionHandling() when debugging a surprising 500: you see the real exception instead of a generic error page.
  • Keep tests in tests/Feature and keep them independent, so they run in any order and in parallel.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does RefreshDatabase do for each test?

    The trait migrates once, then wraps each test in a transaction that is rolled back, so every test starts clean.
  2. 2. Which call signs a user in for a single test request without using the login form?

    actingAs() sets the authenticated user for the request, so the test does not depend on the login flow.
  3. 3. What is the difference between a factory's create() and make()?

    make() returns an unsaved instance. create() inserts a row and returns the saved model.
  4. 4. Why should a validation test also call assertDatabaseCount()?

    An error message alone does not prove nothing was written. Counting rows shows the invalid request had no side effects.

Summary

  • get(), post(), getJson() and friends run a request through your app in memory and return a TestResponse.
  • Use assertStatus(), assertRedirect(), assertJson() and assertJsonPath() to check responses.
  • RefreshDatabase migrates once and rolls back every test; tests run on a separate test database.
  • Factories create realistic data; actingAs() logs a user in; assertDatabaseHas() checks the result.
  • Test the allowed case and the denied or invalid case.

Next: Faking Mail, Queues, Events, HTTP and Time