본문으로 건너뛰기
cccskills
무료GitHub에 공개

tdd-refactor-guard

Pre-refactor safety checklist. Verifies test coverage exists before AI modifies existing code. Use before asking AI to refactor anything.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.0 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

TDD Refactor Guard

A safety gate that runs before any AI-assisted refactoring. Ensures tests exist to catch regressions. If coverage is insufficient, generates characterization tests first.

When This Skill Activates

Use this skill when the user:

  • Says "refactor this" or "clean this up"
  • Wants AI to "restructure" or "reorganize" code
  • Asks to "extract", "inline", "rename", or "simplify" existing code
  • Plans to migrate between patterns (e.g., MVC → MVVM, CoreData → SwiftData)
  • Wants AI to "improve" or "modernize" existing code

Why This Guard Exists

Without guard:               With guard:
"Claude, refactor this"      "Claude, refactor this"
  → AI rewrites code           → Guard checks for tests
  → Something breaks           → Tests missing → generate them
  → You don't know what        → Tests pass → proceed with refactor
  → Debugging nightmare         → Tests fail → exact regression found

Process

Step 1: Identify Scope

What code is being refactored?

Ask user: "Which files/classes are you planning to refactor?"

Or detect from context:

Glob: [files mentioned in conversation]
Read: each file to understand scope

Determine:

  • Files involved
  • Public API surface (methods, properties)
  • Dependencies (what calls this code, what it calls)
  • Side effects (network, disk, notifications, UI updates)

Step 2: Check Existing Test Coverage

Grep: "class.*Tests.*XCTestCase|@Suite.*Tests|struct.*Tests" in test targets
Grep: "@Test|func test" that reference the classes being refactored

Coverage Assessment

LevelCriteriaAction
Good (> 80%)Most public methods have tests for happy + error pathsProceed with refactoring
Partial (40-80%)Some methods tested, missing edge casesAdd characterization tests for uncovered methods
Minimal (< 40%)Few or no testsGenerate full characterization test suite first
None (0%)No test file existsSTOP — create characterization tests before any refactoring

Step 3: Evaluate Test Quality

Even if tests exist, check quality:

// ❌ Low-quality test — doesn't actually verify behavior
@Test("test items")
func testItems() {
    let vm = ViewModel()
    vm.loadItems()
    #expect(true)  // Always passes, tests nothing
}

// ❌ Tests implementation, not behavior
@Test("calls repository")
func testCallsRepo() {
    let vm = ViewModel()
    vm.loadItems()
    #expect(mockRepo.fetchCallCount == 1)  // Brittle
}

// ✅ Tests observable behavior
@Test("loads items into published array")
func testLoadsItems() async {
    let vm = ViewModel(repo: MockRepo(items: [.sample]))
    await vm.loadItems()
    #expect(vm.items.count == 1)
    #expect(vm.items.first?.title == "Sample")
}

Quality checklist:

  • Tests verify outputs/state, not implementation details
  • Both happy path and error paths covered
  • Edge cases (empty, nil, boundary) tested
  • Async behavior properly awaited
  • No #expect(true) or always-passing assertions

Step 4: Generate Missing Tests

If coverage is insufficient, use characterization-test-generator/:

Before refactoring [ClassName], generate characterization tests:
1. Read the source file
2. Identify all public methods
3. Generate tests that capture CURRENT behavior
4. Run and verify all pass

Step 5: Green Light / Red Light

Green Light — Proceed

## Refactor Guard: ✅ PROCEED

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: Good (12 tests covering 8/9 public methods)
**Test quality**: Adequate — tests verify behavior, not implementation

Safe to refactor. Run tests after each change:
`xcodebuild test -scheme YourApp`

Yellow Light — Needs Work

## Refactor Guard: ⚠️ NEEDS TESTS

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: Partial (5 tests covering 4/9 public methods)
**Missing coverage**:
- `ItemManager.sort()` — no test
- `ItemManager.filter(by:)` — no test
- `ItemRepository.sync()` — no test
- Error paths for `save()` and `delete()` — not tested

**Action**: Generate characterization tests for uncovered methods before refactoring.
Use `characterization-test-generator` skill.

Red Light — Stop

## Refactor Guard: 🔴 STOP

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: None (0 tests found)

**Action**: Do NOT refactor until characterization tests exist.
Refactoring without tests is like surgery without monitoring —
you won't know if you killed the patient.

Run `characterization-test-generator` on:
1. ItemManager (7 public methods)
2. ItemRepository (5 public methods)

Then re-run this guard.

Step 6: Post-Refactor Verification

After refactoring is complete:

# Run all tests
xcodebuild test -scheme YourApp

# Check specifically for regressions
xcodebuild test -scheme YourApp \
  -only-testing "YourAppTests/ItemManagerCharacterizationTests"
  • All pre-existing tests still pass
  • Characterization tests still pass
  • No new warnings or errors
  • Public API surface unchanged (unless intentionally changed)

Refactoring Safeguards

Safe Refactorings (Low Risk)

These typically don't change behavior:

  • Rename variable/method/type
  • Extract method/function
  • Inline temporary variable
  • Move method to another type (keeping same behavior)
  • Extract protocol from class

Risky Refactorings (Need Good Coverage)

These can change behavior:

  • Change method signature
  • Reorder operations
  • Replace algorithm
  • Merge/split classes
  • Change data structure
  • Introduce async/await to sync code
  • Migration between frameworks (CoreData → SwiftData)

Migration Refactorings (Need Comprehensive Coverage)

Full contract tests recommended:

  • Architecture change (MVC → MVVM)
  • Framework migration (UIKit → SwiftUI)
  • Storage migration (UserDefaults → SwiftData)
  • Concurrency model change (GCD → async/await)

Output Format

## Refactor Guard Report

**Scope**: [Files/classes to be refactored]
**Verdict**: ✅ PROCEED / ⚠️ NEEDS TESTS / 🔴 STOP

### Coverage Summary
| Class | Public Methods | Tests | Coverage | Verdict |
|-------|---------------|-------|----------|---------|
| ItemManager | 9 | 12 | 89% | ✅ |
| ItemRepository | 5 | 2 | 40% | ⚠️ |

### Missing Coverage
- [ ] `ItemRepository.sync()` — needs characterization test
- [ ] Error path for `ItemRepository.delete()` — untested

### Recommendations
1. [Action item]
2. [Action item]

References

  • testing/characterization-test-generator/ — generates tests this guard may require
  • testing/tdd-feature/ — for building new code during refactor
  • Martin Fowler, Refactoring: Improving the Design of Existing Code

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Run a structured accessibility audit on an iOS/macOS app — automated XCUITest audits, Accessibility Inspector, manual VoiceOver/Dynamic Type passes, and App Store Accessibility Nutrition Label evaluation. Use before release, when preparing Nutrition Label declarations, or for EU Accessibility Act compliance.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

Generate accessibility infrastructure for VoiceOver, Dynamic Type, and accessibility features. Use when improving app accessibility, adding accessibility labels and hints, or auditing compliance.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

Generates an Apple-compliant account deletion flow with multi-step confirmation UI, optional data export, configurable grace period, Keychain cleanup, and server-side deletion request. Use when user needs account deletion, right-to-delete, or Apple App Review compliance for account removal.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

Privacy-preserving ad measurement with AdAttributionKit (SKAdNetwork's successor) — install and re-engagement attribution, conversion-value strategy under crowd anonymity, and end-to-end postback testing. Use when running paid acquisition beyond Apple Ads, measuring re-engagement campaigns, designing conversion values, or migrating from SKAdNetwork.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

alarmkit

무료

AlarmKit integration for scheduling alarms and timers with custom UI, Live Activities, and snooze support. Use when implementing alarm or timer features in iOS 26+ apps.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

Interpret app metrics and make data-driven decisions. Covers DAU/MAU, retention, LTV, ARPU, App Store Connect analytics, AARRR funnel analysis, cohort analysis, and diagnostic decision trees. Use when user wants to understand their metrics, diagnose problems, or build a data-driven growth plan.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

rshankras/claude-code-apple-skills8132026년 7월 24일 업데이트

rshankras의 스킬 모두 보기

이 스킬의 문제 신고