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

Laravel Tdd

  • 1.4k installs
  • 238k repo stars
  • Updated August 5, 2026
  • affaan-m/ecc

This is a copy of laravel-tdd by affaan-m - installs and ranking accrue to the original listing.

laravel-tdd is an agent skill that guides test-driven development when creating Laravel features, models, and APIs with PHPUnit, Pest, factories, and 80%+ test coverage for developers building PHP backends.

About

laravel-tdd is an affaan-m/ecc skill for test-driven development on Laravel applications using PHPUnit and Pest with an 80%+ coverage target across unit and feature tests. It follows a red-green-refactor cycle: write a failing test, implement code to pass, then refactor. The skill covers Eloquent models, policies, jobs, notifications, database factories, fakes, and new API endpoints. Pest is preferred for new tests unless the project is already standardized on PHPUnit. Developers reach for laravel-tdd when adding Laravel features, fixing bugs with regression tests, or refactoring with safety nets. It triggers on new endpoints, model changes, and any Laravel work where coverage and TDD discipline are required.

  • Red-Green-Refactor cycle for Laravel applications
  • Tests Eloquent models, relationships, scopes and accessors
  • HTTP feature tests for controllers and form requests
  • Sanctum and Passport authentication testing
  • Mocking for queues, mail, notifications and external HTTP services

Laravel Tdd by the numbers

  • 1,389 all-time installs (skills.sh)
  • +85 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/affaan-m/ecc --skill laravel-tdd

Add your badge

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

Listed on Skillselion
Installs1.4k
repo stars238k
Last updatedAugust 5, 2026
Repositoryaffaan-m/ecc

How do you do TDD in Laravel with Pest?

Follow test-driven development when creating Laravel features, models, and APIs with full test coverage.

Who is it for?

PHP developers building Laravel APIs and backend features who want red-green-refactor discipline with Pest or PHPUnit.

Skip if: Frontend-only React work, non-PHP frameworks, or teams that explicitly skip automated test coverage on Laravel code.

When should I use this skill?

The user adds Laravel features, endpoints, models, or bug fixes and needs TDD with PHPUnit or Pest.

What you get

PHPUnit or Pest test suites with factories, fakes, and 80%+ unit and feature coverage for Laravel code.

  • Pest or PHPUnit test files
  • Laravel feature implementations
  • database factories and fakes

By the numbers

  • laravel-tdd targets 80%+ unit and feature test coverage on Laravel applications

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

How it compares

Pick laravel-tdd for Laravel-specific TDD with factories and policies; use generic PHPUnit skills for non-Laravel PHP projects.

FAQ

What coverage target does laravel-tdd set?

laravel-tdd targets 80%+ test coverage across unit and feature tests when building Laravel applications with PHPUnit and Pest, factories, database fakes, and the red-green-refactor cycle.

Should laravel-tdd use Pest or PHPUnit?

laravel-tdd prefers Pest for new tests unless the project is already standardized on PHPUnit. Both frameworks are supported for models, policies, jobs, notifications, and API endpoints.

Testing & QAbackendtesting

This week in AI coding

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

unsubscribe anytime.