Skip to content

Refactor a Test Suite for DRY Using AI

Test Code ReviewUpdated 2026-10-11intermediate
TL;DR

Scans a set of test files and identifies duplicated setup, fixture state, and assertion patterns: proposes refactors using Playwright fixtures, factory functions, or shared helper modules with concrete code diffs. Warns against premature abstraction (single-use helpers).

When to use it

  • Test suite has grown to 20+ files with copy-paste duplication.
  • Onboarding pain because new tests are written by copying existing ones.
  • Adding shared concerns (logging, instrumentation) consistently across tests.
  • Refactoring before a major framework upgrade: DRY first, then upgrade is easier.

The prompt

XML-tagged: works best with Claude
dry-refactor-test-suite.claude.mdprompt
<role>You are a test infrastructure engineer. You know that DRY in tests is a balance: too much abstraction hides intent; too little creates rot. You propose refactors that pay back in maintenance, not premature ones.</role> <context>Common DRY opportunities in tests:- **beforeEach duplication**: same setup steps in multiple files → fixture- **Helper duplication**: same helper function defined inline in multiple files → shared module- **Assertion pattern duplication**: same group of assertions on the same object shape → custom matcher / assertion helper- **Test data duplication**: same fixtures (users, products) created inline → factory function- **POM duplication**: same UI flow scripted in multiple specs → POM method Anti-pattern: extracting a helper used ONLY ONCE. Inline > abstraction when called from one place.</context> <task>For the test files I provide:1. Identify EXACT duplication (3+ occurrences of same logic).2. Identify NEAR duplication (2+ occurrences with minor variation).3. Propose refactor per duplication:   - For setup → Playwright fixture (or Jest `beforeEach` helper)   - For data → factory function   - For assertion → custom matcher or assertion helper   - For UI flow → POM method4. Diff-style output showing the new shared module + per-file diff.5. Warn against premature abstraction: single-use helpers should be inlined.</task> <input>Test files (paths + content): {test_files}Framework: {framework}Existing shared modules (if any): {existing_shared}</input> <constraints>- Threshold: 3+ exact duplications, OR 2+ near-duplications with > 80% similarity.- Single-use helpers FLAG as anti-pattern, not as refactor candidate.- Diffs MUST be diff-style (/+) showing exact lines added/removed.- Suggested abstraction names should be domain-specific (not `utilA`, `helperX`).- Note any shared concern that's organizational (e.g., logging) vs functional (test logic).</constraints> <output_format>Three sections:1. **Duplication inventory**: table: Pattern | Occurrences | Files | Recommended refactor2. **Refactor diffs**: per refactor, show new shared file + per-file modification3. **Warnings**: flag single-use helpers and other premature-abstraction risks</output_format> <approach>Before writing, count occurrences of each candidate pattern: single occurrences are NOT refactor candidates.</approach>

Example

Input
Test files:

```typescript
// tests/checkout/cart.spec.ts
test('add to cart', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.getByLabel('Email').fill('test@example.com');
  await page.getByLabel('Password').fill('TestPass123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/\/dashboard/);
  // ... rest of cart test
});

// tests/checkout/discount.spec.ts
test('apply discount', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.getByLabel('Email').fill('test@example.com');
  await page.getByLabel('Password').fill('TestPass123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/\/dashboard/);
  // ... rest of discount test
});

// tests/profile/edit.spec.ts
test('edit profile', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.getByLabel('Email').fill('test@example.com');
  await page.getByLabel('Password').fill('TestPass123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/\/dashboard/);
  // ... rest of profile test
});

// tests/checkout/refund.spec.ts (uses different test user)
test('refund order', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.getByLabel('Email').fill('admin@example.com');
  await page.getByLabel('Password').fill('AdminPass123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL(/\/admin/);
  // ... rest of refund test
});
```

Framework: Playwright
Existing shared modules: None, currently flat structure.
Output
## 1. Duplication inventory

| Pattern | Occurrences | Files | Recommended refactor |
|---------|-------------|-------|----------------------|
| Sign-in flow (goto → fill email → fill password → click) | 4 | cart.spec.ts, discount.spec.ts, edit.spec.ts, refund.spec.ts | Playwright fixture: `authenticatedAs(role)` returning a logged-in page |
| Test user credentials | 4 | (same files; 3 use test user, 1 uses admin) | Test users module `tests/fixtures/users.ts` |
| Post-sign-in URL assertion | 4 | (same files) | Inside the fixture; tests don't need to repeat |

## 2. Refactor diffs

### New file: `tests/fixtures/users.ts`

```typescript
export const USERS = {
  member: { email: 'test@example.com', password: 'TestPass123', expectedRedirect: /\/dashboard/ },
  admin: { email: 'admin@example.com', password: 'AdminPass123', expectedRedirect: /\/admin/ },
} as const;

export type UserRole = keyof typeof USERS;
```

### New file: `tests/fixtures/authenticated-page.ts`

```typescript
import { test as base, expect } from '@playwright/test';
import { USERS, type UserRole } from './users';

export type AuthFixtures = {
  authenticatedAs: (role: UserRole) => Promise<void>;
};

export const test = base.extend<AuthFixtures>({
  authenticatedAs: async ({ page }, use) => {
    await use(async (role: UserRole) => {
      const user = USERS[role];
      await page.goto('/');
      await page.getByRole('button', { name: 'Sign in' }).click();
      await page.getByLabel('Email').fill(user.email);
      await page.getByLabel('Password').fill(user.password);
      await page.getByRole('button', { name: 'Sign in' }).click();
      await expect(page).toHaveURL(user.expectedRedirect);
    });
  },
});

export { expect } from '@playwright/test';
```

### Modified: `tests/checkout/cart.spec.ts` (diff)

```diff
-import { test, expect } from '@playwright/test';
+import { test, expect } from '../fixtures/authenticated-page';

-test('add to cart', async ({ page }) => {
-  await page.goto('/');
-  await page.getByRole('button', { name: 'Sign in' }).click();
-  await page.getByLabel('Email').fill('test@example.com');
-  await page.getByLabel('Password').fill('TestPass123');
-  await page.getByRole('button', { name: 'Sign in' }).click();
-  await expect(page).toHaveURL(/\/dashboard/);
+test('add to cart', async ({ page, authenticatedAs }) => {
+  await authenticatedAs('member');
   // ... rest of cart test (unchanged)
 });
```

(Apply the same diff to `discount.spec.ts` and `edit.spec.ts`: all using `authenticatedAs('member')`.)

### Modified: `tests/checkout/refund.spec.ts` (diff)

```diff
-import { test, expect } from '@playwright/test';
+import { test, expect } from '../fixtures/authenticated-page';

-test('refund order', async ({ page }) => {
-  await page.goto('/');
-  await page.getByRole('button', { name: 'Sign in' }).click();
-  await page.getByLabel('Email').fill('admin@example.com');
-  await page.getByLabel('Password').fill('AdminPass123');
-  await page.getByRole('button', { name: 'Sign in' }).click();
-  await expect(page).toHaveURL(/\/admin/);
+test('refund order', async ({ page, authenticatedAs }) => {
+  await authenticatedAs('admin');
   // ... rest of refund test (unchanged)
 });
```

## 3. Warnings

- **No single-use helpers detected**: the proposed refactors all have 2+ usages.
- **Consider session reuse for further optimization**: instead of going through the UI sign-in on every test, use Playwright's `storageState` to save auth state once and reuse. This is an optimization for after the initial DRY refactor; it reduces test runtime by ~2-5s per test.
- **Don't extract POM methods that are used only in one spec**: common temptation when refactoring; resist. Inline > one-time abstraction.
- **Be cautious of the `tests/fixtures/` folder growing into a kitchen sink**. As more fixtures are added, organize by feature (`fixtures/auth.ts`, `fixtures/cart.ts`), not as one giant module.

Common pitfalls

  • Model proposes extracting single-use helpers: anti-pattern; force the 3+ occurrence rule.
  • Refactors lose context (helpers named `helper1`, `utilA`); insist on domain-named abstractions.
  • Diffs aren't really diffs (just rewritten files), make sure, / + format is used.
  • Over-abstracts data (factory for a 2-line user object): sometimes inline data is clearer.

Tips

  • Refactor in a separate PR: don't bundle DRY refactor with new test additions.
  • After refactor, run the whole suite to ensure behavior is unchanged.
  • Pair with `generate-playwright-pom` for UI flows that deserve POM extraction.
  • Pair with `pom-refactoring-reviewer` to verify the new abstractions don't violate POM principles.

FAQ

When does DRY hurt in tests?

When test setup becomes a chain of abstractions that obscures what the test is actually exercising. If you have to navigate through 3 helper files to understand a single test, the abstractions are too deep. Inline beats abstraction when an abstraction has only 2-3 callers.

Playwright fixture scope levels: when to use which?

Test scope (default): set up per test, torn down after. Worker scope: shared across tests in one worker, useful for expensive setup. Module / file scope: not natively supported, use beforeAll within a describe. Test scope is right for ~95% of cases.

Helpers vs fixtures: what's the difference?

Helpers are plain functions you call; you manage their lifecycle. Fixtures use `test.extend` and integrate with Playwright's setup/teardown. Prefer fixtures for anything with lifecycle (browser state, auth, DB connection). Helpers for pure utility functions.

How do I know if I've over-refactored?

If new contributors take longer to understand the suite than to write a new test from scratch: you've over-refactored. Strip back. Keep DRY where it pays maintenance dividends; let small duplication stand where it doesn't.