Topics Testing Feature Tests & HTTP Testing
intermediate 16 min read

Feature Tests & HTTP Testing

HTTP tests, database assertions, authentication testing, and JSON API testing.

HTTP Tests

namespace Tests\Feature;

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

class PostTest extends TestCase
{
use RefreshDatabase;

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

$response = $this->actingAs($user)->post("/posts", [
"title" => "My First Post",
"body" => "This is the body content.",
]);

$response->assertStatus(302);
$response->assertSessionHas("success");
$this->assertDatabaseHas("posts", ["title" => "My First Post"]);
}
}

JSON API Tests

$response = $this->actingAs($user)
->getJson("/api/v1/posts");

$response->assertStatus(200)
->assertJsonStructure(["data" => ["*" => ["id", "title"]], "meta"]);

Database Assertions

$this->assertDatabaseHas("users", ["email" => "[email protected]"]);
$this->assertDatabaseMissing("users", ["email" => "[email protected]"]);
$this->assertDatabaseCount("posts", 5);
$this->assertModelExists($user);

Examples

<?php
namespace Tests\Feature;

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

class AuthenticationTest extends TestCase
{
    use RefreshDatabase;

    public function test_login_redirects_to_dashboard(): void
    {
        \$user = User::factory()->create(['password' => bcrypt('password')]);
        \$response = \$this->post('/login', ['email' => \$user->email, 'password' => 'password']);
        \$response->assertRedirect('/dashboard');
        \$this->assertAuthenticatedAs(\$user);
    }
}

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.