Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
affaan-m avatar

Laravel Tdd

  • 5.5k installs
  • 234k repo stars
  • Updated July 27, 2026
  • affaan-m/everything-claude-code

laravel-tdd is an agent skill that guides test-driven Laravel development with PHPUnit, Pest, factories, fakes, and 80 percent plus coverage.

About

The laravel-tdd skill teaches test-driven development for Laravel applications using PHPUnit and Pest with an 80 percent plus coverage target across unit, feature, and integration layers. The red-green-refactor cycle starts with a failing test, implements the minimal passing code, then refactors while keeping tests green. Unit tests cover pure PHP classes, value objects, and services. Feature tests target HTTP endpoints, authentication, validation, policies, and response shape. Integration tests combine database, queues, and external boundaries. Database strategy defaults to RefreshDatabase for feature and integration work, with DatabaseTransactions when schema is already migrated and DatabaseMigrations when full fresh runs are required. Prefer Pest for new tests unless the project standardizes PHPUnit. Factories with states supply test data. Fakes isolate jobs, queues, mail, notifications, and events. Http::fake handles external APIs. Sanctum actingAs covers API auth. Inertia responses use assertInertia helpers. Coverage runs via php artisan test with pcov or XDEBUG_MODE=coverage in CI.

  • Red-green-refactor TDD cycle with unit, feature, and integration test layer guidance
  • RefreshDatabase default for database tests plus Pest preference over PHPUnit for new suites
  • Factories with states, assertDatabaseHas, and isolated fakes for jobs, mail, queues, and events
  • Feature tests for HTTP, Sanctum auth, policies, Gates, and Inertia assertInertia responses
  • 80 percent plus coverage target using php artisan test, pcov, or XDEBUG_MODE=coverage in CI

Laravel Tdd by the numbers

  • 5,483 all-time installs (skills.sh)
  • +309 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #3 of 65 PHP & Laravel skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

laravel-tdd capabilities & compatibility

Capabilities
red green refactor tdd cycle · pest and phpunit test suites · refresh database isolation · laravel fakes jobs mail queue · sanctum and inertia testing
Use cases
testing · api development · refactoring
From the docs

What laravel-tdd says it does

Desarrollo guiado por pruebas para aplicaciones Laravel usando PHPUnit y Pest con 80%+ de cobertura (unit + feature).
SKILL.md
Usar `RefreshDatabase` como predeterminado para pruebas que tocan la base de datos
SKILL.md
Usar **Pest** por defecto para pruebas nuevas cuando esté disponible.
SKILL.md
npx skills add https://github.com/affaan-m/everything-claude-code --skill laravel-tdd

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs5.5k
repo stars234k
Security audit3 / 3 scanners passed
Last updatedJuly 27, 2026
Repositoryaffaan-m/everything-claude-code

How do I structure PHPUnit or Pest tests for Laravel endpoints, Eloquent models, jobs, and external APIs with reliable database isolation?

Write Laravel TDD tests with PHPUnit or Pest, factories, database traits, fakes, and 80 percent plus coverage targets.

Who is it for?

Laravel teams adding features, fixing bugs, or refactoring controllers, models, policies, jobs, and notifications with TDD discipline.

Skip if: Skip when the stack is not Laravel or when the task is deployment, frontend-only work, or manual QA without automated tests.

When should I use this skill?

User adds Laravel endpoints, tests Eloquent models or policies, refactors with failing tests first, or sets up Pest or PHPUnit coverage in CI.

What you get

Passing unit, feature, and integration tests with factories, fakes, database traits, and measurable 80 percent plus code coverage.

  • PHPUnit or Pest test files
  • Factory definitions with states
  • CI coverage report

By the numbers

  • 80 percent plus coverage target
  • 3 test layers: unit, feature, integration

Files

SKILL.mdMarkdownGitHub ↗

Flujo de Trabajo TDD en Laravel

Desarrollo guiado por pruebas para aplicaciones Laravel usando PHPUnit y Pest con 80%+ de cobertura (unit + feature).

Cuándo Usar

  • Nuevas funcionalidades o endpoints en Laravel
  • Correcciones de bugs o refactorizaciones
  • Probar modelos Eloquent, policies, jobs y notifications
  • Preferir Pest para pruebas nuevas a menos que el proyecto ya esté estandarizado en PHPUnit

Cómo Funciona

Ciclo Rojo-Verde-Refactorizar

1) Escribir una prueba fallida 2) Implementar el cambio mínimo para que pase 3) Refactorizar manteniendo las pruebas en verde

Capas de Prueba

  • Unit: clases PHP puras, objetos de valor, servicios
  • Feature: endpoints HTTP, autenticación, validación, policies
  • Integration: base de datos + colas + límites externos

Elegir capas según el alcance:

  • Usar pruebas Unit para lógica de negocio pura y servicios.
  • Usar pruebas Feature para HTTP, autenticación, validación y forma de respuesta.
  • Usar pruebas Integration cuando se validen BD/colas/servicios externos juntos.

Estrategia de Base de Datos

  • RefreshDatabase para la mayoría de pruebas feature/integration (ejecuta migraciones una vez por ejecución de prueba, luego envuelve cada prueba en una transacción cuando está soportado; las bases de datos en memoria pueden re-migrar por prueba)
  • DatabaseTransactions cuando el esquema ya está migrado y solo se necesita rollback por prueba
  • DatabaseMigrations cuando se necesita un migrate/fresh completo para cada prueba y se puede asumir el costo

Usar RefreshDatabase como predeterminado para pruebas que tocan la base de datos: para bases de datos con soporte de transacciones, ejecuta las migraciones una vez por ejecución de prueba (mediante un flag estático) y envuelve cada prueba en una transacción; para SQLite :memory: o conexiones sin transacciones, migra antes de cada prueba. Usar DatabaseTransactions cuando el esquema ya está migrado y solo se necesitan rollbacks por prueba.

Elección del Framework de Pruebas

  • Usar Pest por defecto para pruebas nuevas cuando esté disponible.
  • Usar PHPUnit solo si el proyecto ya lo estandariza o requiere herramientas específicas de PHPUnit.

Ejemplos

Ejemplo con PHPUnit

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

final class ProjectControllerTest extends TestCase
{
    use RefreshDatabase;

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

        $response = $this->actingAs($user)->postJson('/api/projects', [
            'name' => 'New Project',
        ]);

        $response->assertCreated();
        $this->assertDatabaseHas('projects', ['name' => 'New Project']);
    }
}

Ejemplo de Prueba Feature (Capa HTTP)

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

final class ProjectIndexTest extends TestCase
{
    use RefreshDatabase;

    public function test_projects_index_returns_paginated_results(): void
    {
        $user = User::factory()->create();
        Project::factory()->count(3)->for($user)->create();

        $response = $this->actingAs($user)->getJson('/api/projects');

        $response->assertOk();
        $response->assertJsonStructure(['success', 'data', 'error', 'meta']);
    }
}

Ejemplo con Pest

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

use function Pest\Laravel\actingAs;
use function Pest\Laravel\assertDatabaseHas;

uses(RefreshDatabase::class);

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

    $response = actingAs($user)->postJson('/api/projects', [
        'name' => 'New Project',
    ]);

    $response->assertCreated();
    assertDatabaseHas('projects', ['name' => 'New Project']);
});

Ejemplo de Prueba Feature con Pest (Capa HTTP)

use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

use function Pest\Laravel\actingAs;

uses(RefreshDatabase::class);

test('projects index returns paginated results', function () {
    $user = User::factory()->create();
    Project::factory()->count(3)->for($user)->create();

    $response = actingAs($user)->getJson('/api/projects');

    $response->assertOk();
    $response->assertJsonStructure(['success', 'data', 'error', 'meta']);
});

Factories y Estados

  • Usar factories para datos de prueba
  • Definir estados para casos límite (archivado, admin, trial)
$user = User::factory()->state(['role' => 'admin'])->create();

Pruebas de Base de Datos

  • Usar RefreshDatabase para estado limpio
  • Mantener las pruebas aisladas y deterministas
  • Preferir assertDatabaseHas sobre consultas manuales

Ejemplo de Prueba de Persistencia

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

final class ProjectRepositoryTest extends TestCase
{
    use RefreshDatabase;

    public function test_project_can_be_retrieved_by_slug(): void
    {
        $project = Project::factory()->create(['slug' => 'alpha']);

        $found = Project::query()->where('slug', 'alpha')->firstOrFail();

        $this->assertSame($project->id, $found->id);
    }
}

Fakes para Efectos Secundarios

  • Bus::fake() para jobs
  • Queue::fake() para trabajo en cola
  • Mail::fake() y Notification::fake() para notificaciones
  • Event::fake() para eventos de dominio
use Illuminate\Support\Facades\Queue;

Queue::fake();

dispatch(new SendOrderConfirmation($order->id));

Queue::assertPushed(SendOrderConfirmation::class);
use Illuminate\Support\Facades\Notification;

Notification::fake();

$user->notify(new InvoiceReady($invoice));

Notification::assertSentTo($user, InvoiceReady::class);

Pruebas de Autenticación (Sanctum)

use Laravel\Sanctum\Sanctum;

Sanctum::actingAs($user);

$response = $this->getJson('/api/projects');
$response->assertOk();

HTTP y Servicios Externos

  • Usar Http::fake() para aislar APIs externas
  • Verificar payloads salientes con Http::assertSent()

Objetivos de Cobertura

  • Aplicar 80%+ de cobertura para pruebas unit + feature
  • Usar pcov o XDEBUG_MODE=coverage en CI

Comandos de Prueba

  • php artisan test
  • vendor/bin/phpunit
  • vendor/bin/pest

Configuración de Pruebas

  • Usar phpunit.xml para establecer DB_CONNECTION=sqlite y DB_DATABASE=:memory: para pruebas rápidas
  • Mantener un entorno separado para pruebas para evitar tocar datos de desarrollo/producción

Pruebas de Autorización

use Illuminate\Support\Facades\Gate;

$this->assertTrue(Gate::forUser($user)->allows('update', $project));
$this->assertFalse(Gate::forUser($otherUser)->allows('update', $project));

Pruebas Feature con Inertia

Al usar Inertia.js, verificar el nombre del componente y las props con los helpers de testing de Inertia.

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

final class DashboardInertiaTest extends TestCase
{
    use RefreshDatabase;

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

        $response = $this->actingAs($user)->get('/dashboard');

        $response->assertOk();
        $response->assertInertia(fn (AssertableInertia $page) => $page
            ->component('Dashboard')
            ->where('user.id', $user->id)
            ->has('projects')
        );
    }
}

Preferir assertInertia sobre aserciones JSON crudas para mantener las pruebas alineadas con las respuestas de Inertia.

Related skills

Forks & variants (1)

Laravel Tdd has 1 known copy in the catalog totaling 1.3k installs. They canonicalize to this original listing.

How it compares

Pick laravel-tdd when building Laravel backend features test-first; use generic PHPUnit skills when the stack is not Laravel-specific.

FAQ

Should I use Pest or PHPUnit for new Laravel tests?

Prefer Pest for new tests unless the project already standardizes on PHPUnit or needs PHPUnit-specific tooling.

Which database trait should Laravel feature tests use?

Default to RefreshDatabase; use DatabaseTransactions when schema is migrated and DatabaseMigrations when each test needs a full fresh migrate.

What coverage target does laravel-tdd recommend?

Aim for 80 percent plus coverage across unit and feature tests using pcov or XDEBUG_MODE=coverage in CI.

Is Laravel Tdd safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

PHP & Laraveltestingbackend

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.