본문으로 건너뛰기
Skillpedia
테스트280k · #201

laravel-tdd

하는 일

이 도구는 Laravel 코드의 자동 테스트를 만드는 데 도움을 줍니다. 애플리케이션이 기대대로 작동하도록 보장하고, 오류를 빨리 찾아내는 데 도움을 줍니다.

사용하는 경우

  • ✓Laravel 애플리케이션의 새로운 부분을 만들 때.
  • ✓애플리케이션에 새로운 기능을 추가할 때.
  • ✓코드 변경으로 기존 기능이 망가지지 않았는지 확인하고 싶을 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-tdd/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-tdd/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“새 사용자가 정상적으로 만들어지는지 확인하는 테스트를 작성해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

먼저 실패하는 테스트를 작성한 다음, 테스트를 통과하도록 코드를 작성합니다. 마지막으로 테스트가 계속 통과하는 상태에서 코드를 개선합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Laravel Testing with TDD

Test-driven development for Laravel applications using PHPUnit, Pest, Laravel factories, and testing helpers.

When to Activate

  • Writing new Laravel applications or features
  • Implementing API endpoints with Sanctum or Passport authentication
  • Testing Eloquent models, relationships, scopes, and accessors
  • Setting up testing infrastructure for Laravel projects
  • Writing feature tests for HTTP controllers and form requests
  • Mocking external services (queues, mail, notifications, HTTP)

TDD Workflow for Laravel

Red-Green-Refactor Cycle

// Step 1: RED — Write a failing test
public function test_a_product_can_be_created(): void
{
    $product = Product::factory()->create(['name' => 'Test Product']);
    $this->assertDatabaseHas('products', ['name' => 'Test Product']);
}

// Step 2: GREEN — Write the migration, model, and factory
// Step 3: REFACTOR — Improve while keeping tests green

Setup

PHPUnit Configuration

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">tests/Feature</directory>
        </testsuite>
    </testsuites>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_STORE" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
    </php>
</phpunit>

Base TestCase Setup

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        // Call $this->withoutExceptionHandling() only in tests that
        // test non-HTTP exceptions; it suppresses assertStatus() etc.
    }

    // Helper: Authenticate and return user
    protected function actingAsUser(): mixed
    {
        $user = \App\Models\User::factory()->create();
        $this->actingAs($user);
        return $user;
    }

    protected function actingAsAdmin(): mixed
    {
        $admin = \App\Models\User::factory()->admin()->create();
        $this->actingAs($admin);
        return $admin;
    }
}

Model Factories

// database/factories/UserFactory.php
class UserFactory extends Factory
{
    protected static ?string $password = null;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
            'role' => 'user',
        ];
    }

    public function admin(): static
    {
        return $this->state(fn (array $attributes) => ['role' => 'admin']);
    }

    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => ['email_verified_at' => null]);
    }
}

// database/factories/ProductFactory.php
class ProductFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->unique()->words(3, true),
            'slug' => fn (array $attrs) => Str::slug($attrs['name']),
            'description' => fake()->paragraph(),
            'price' => fake()->numberBetween(100, 100000),
            'stock' => fake()->numberBetween(0, 100),
            'is_active' => true,
            'user_id' => UserFactory::new(),
        ];
    }

    public function outOfStock(): static
    {
        return $this->state(fn (array $attributes) => ['stock' => 0]);
    }
}

Using Factories

$user = User::factory()->create();
$admin = User::factory()->admin()->create();
$product = Product::factory()->create(['user_id' => $user->id]);
$products = Product::factory()->count(10)->create();
$draft = Product::factory()->make(); // Not persisted

// With relationships

…
자주 묻는 질문

TDD란 무엇인가요?

‘테스트 주도 개발(Test-Driven Development)’의 약자입니다. 실제 코드를 작성하기 전에 테스트를 먼저 작성하는 프로그래밍 방식입니다.

‘모델 팩토리’란 무엇인가요?

데이터베이스 모델의 테스트 데이터를 쉽게 만들 수 있도록 미리 준비된 템플릿과 같습니다. 테스트에 사용할 예시 데이터를 손쉽게 생성하게 해 줍니다.

PHPUnit이나 Pest는 무엇인가요?

PHP에서 자동 테스트를 작성하고 실행할 때 널리 쓰이는 도구들입니다.

상세 정보

작성자의 원본 설명

Laravel testing strategies with PHPUnit, Pest, model factories, HTTP tests, Sanctum authentication testing, mocking, and coverage. Use when writing Laravel tests with PHPUnit or Pest, or driving a Laravel feature test-first.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#201
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬