Skip to main content
skill CX Codex

integration-test-builder — skill for Claude Code: API tests with DB

integration-test-builder — a skill for building integration tests for APIs and database flows. Generates test harness, fixtures, setup/teardown, database seeding, and CI-ready strategies.

MIT 267 installs ★ 64 updated 2026-01-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add patricio0312rev/skills --skill integration-test-builder -a claude-code
Open on GitHub

What integration-test-builder does

The skill constructs a complete integration test suite: sets up a test database, writes fixtures, creates setup and teardown hooks, clears tables between runs. Includes examples for CRUD operations, error handling (400, 404, 409), and transactions with rollback on failure. Uses supertest for HTTP calls, Prisma for database access, execSync for migrations.

Tests follow Arrange-Act-Assert: prepare data, send request, verify response and database state. The harness automatically clears tables before each test (except the _prisma_migrations table) to avoid state leaks. Requires a separate TEST_DATABASE_URL — otherwise conflicts with production data.

What it helps with

  • write integration tests for REST APIs with database verification
  • set up test harness with automatic seeding and cleanup
  • test transactions and rollbacks on errors
  • prepare tests for CI pipelines without state pollution

Example prompts for the agent

  • Generate integration tests for POST /users with duplicate and email validation checks
  • Create test harness with fixtures for user and product, including seeding and database cleanup
  • Write tests for successful order creation with transaction rollback if stock is insufficient

How to install integration-test-builder

1Skills CLI (Vercel)

npx skills add patricio0312rev/skills --skill integration-test-builder -a claude-code

2Manually: put the files in place

~/.claude/skills/integration-test-builder/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/integration-test-builder/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about integration-test-builder

How do I install integration-test-builder in Claude Code?

Run npx skills add patricio0312rev/skills --skill integration-test-builder -a claude-code. The skill will appear at ~/.claude/skills/integration-test-builder/SKILL.md.

What does integration-test-builder do?

Generates a complete integration test suite: test harness with setup/teardown, fixtures, CRUD test examples, error checking, and transactions. Automatically clears the database between tests and handles migrations through Prisma.

What do I need to use this skill?

A separate test database with TEST_DATABASE_URL set, Prisma for migrations, supertest for HTTP requests. The skill assumes PostgreSQL for TRUNCATE CASCADE, but the logic adapts easily to other databases.

Source text

SKILL.md · MIT
---
name: integration-test-builder
description: Creates integration tests for API endpoints with database flows, including test harness setup, fixtures, setup/teardown, database seeding, and CI-friendly strategies. Use for "integration testing", "API tests", "database tests", or "test harness".
---

# Integration Test Builder

Build comprehensive integration tests for APIs and database flows.

## Test Harness Setup

```typescript
// tests/setup/test-harness.ts
import { PrismaClient } from "@prisma/client";
import { execSync } from "child_process";

export class TestHarness {
  prisma: PrismaClient;

  async setup() {
    // Setup test database
    process.env.DATABASE_URL = process.env.TEST_DATABASE_URL;

    // Run migrations
    execSync("npx prisma migrate deploy");

    // Initialize Prisma client
    this.prisma = new PrismaClient();

    // Clear all data
    await this.clearDatabase();
  }

  async teardown() {
    await this.prisma.$disconnect();
  }

  async clearDatabase() {
    const tables = await this.prisma.$queryRaw<{ tablename: string }[]>`
      SELECT tablename FROM pg_tables WHERE schemaname = 'public'
    `;

    for (const { tablename } of tables) {
      if (tablename !== "_prisma_migrations") {
        await this.prisma.$executeRawUnsafe(
          `TRUNCATE TABLE "${tablename}" CASCADE`
        );
      }
    }
  }

  async seedFixtures() {
    // Seed test data
    await this.prisma.user.create({
      data: {
        email: "[email protected]",
        name: "Test User",
      },
    });
  }
}
```

## API Integration Tests

```typescript
// tests/api/users.test.ts
import request from "supertest";
import { app } from "@/app";
import { TestHarness } from "../setup/test-harness";

describe("User API", () => {
  let harness: TestHarness;

  beforeAll(async () => {
    harness = new TestHarness();
    await harness.setup();
  });

  afterAll(async () => {
    await harness.teardown();
  });

  beforeEach(async () => {
    await harness.clearDatabase();
    await harness.seedFixtures();
  });

  describe("POST /api/users", () => {
    it("should create new user", async () => {
      // Arrange
      const userData = {
        email: "[email protected]",
        name: "New User",
      };

      // Act
      const response = await request(app)
        .post("/api/users")
        .send(userData)
        .expect(201);

      // Assert
      expect(response.body).toMatchObject({
        email: userData.email,
        name: userData.name,
      });
      expect(response.body.id).toBeDefined();

      // Verify in database
      const user = await harness.prisma.user.findUnique({
        where: { email: userData.email },
      });
      expect(user).toBeDefined();
      expect(user!.name).toBe(userData.name);
    });

    it("should return 400 for invalid email", async () => {
      // Arrange
      const userData = {
        email: "invalid-email",
        name: "Test User",
      };

      // Act
      const response = await request(app)
        .post("/api/users")
        .send(userData)
        .expect(400);

      // Assert
      expect(response.body.error).toContain("Invalid email");
    });

    it("should return 409 for duplicate email", async () => {
      // Arrange
      const userData = {
        email: "[email protected]", // Already exists
        name: "Duplicate User",
      };

      // Act
      const response = await request(app)
        .post("/api/users")
        .send(userData)
        .expect(409);

      // Assert
      expect(response.body.error).toContain("already exists");
    });
  });

  describe("GET /api/users/:id", () => {
    it("should get user by id", async () => {
      // Arrange
      const user = await harness.prisma.user.findFirst();

      // Act
      const response = await request(app)
        .get(`/api/users/${user!.id}`)
        .expect(200);

      // Assert
      expect(response.body).toMatchObject({
        id: user!.id,
        email: user!.email,
        name: user!.name,
      });
    });

    it("should return 404 for non-existent user", async () => {
      // Act
      const response = await request(app).get("/api/users/99999").expect(404);

      // Assert
      expect(response.body.error).toContain("not found");
    });
  });

  describe("PUT /api/users/:id", () => {
    it("should update user", async () => {
      // Arrange
      const user = await harness.prisma.user.findFirst();
      const updates = { name: "Updated Name" };

      // Act
      const response = await request(app)
        .put(`/api/users/${user!.id}`)
        .send(updates)
        .expect(200);

      // Assert
      expect(response.body.name).toBe("Updated Name");

      // Verify in database
      const updatedUser = await harness.prisma.user.findUnique({
        where: { id: user!.id },
      });
      expect(updatedUser!.name).toBe("Updated Name");
    });
  });

  describe("DELETE /api/users/:id", () => {
    it("should delete user", async () => {
      // Arrange
      const user = await harness.prisma.user.findFirst();

      // Act
      await request(app).delete(`/api/users/${user!.id}`).expect(204);

      // Assert - verify deletion in database
      const deletedUser = await harness.prisma.user.findUnique({
        where: { id: user!.id },
      });
      expect(deletedUser).toBeNull();
    });
  });
});
```

## Database Transaction Tests

```typescript
// tests/integration/order-flow.test.ts
describe("Order Flow", () => {
  it("should create order with items in transaction", async () => {
    // Arrange
    const user = await harness.prisma.user.findFirst();
    const product = await harness.prisma.product.create({
      data: {
        name: "Test Product",
        price: 99.99,
        stock: 10,
      },
    });

    const orderData = {
      userId: user!.id,
      items: [
        {
          productId: product.id,
          quantity: 2,
          price: product.price,
        },
      ],
    };

    // Act
    const response = await request(app)
      .post("/api/orders")
      .send(orderData)
      .expect(201);

    // Assert
    const order = await harness.prisma.order.findUnique({
      where: { id: response.body.id },
      include: { items: true },
    });

    expect(order).toBeDefined();
    expect(order!.items).toHaveLength(1);
    expect(order!.items[0].quantity).toBe(2);

    // Verify stock was decremented
    const updatedProduct = await harness.prisma.product.findUnique({
      where: { id: product.id },
    });
    expect(updatedProduct!.stock).toBe(8); // 10 - 2
  });

  it("should rollback transaction if order creation fails", async () => {
    // Arrange
    const user = await harness.prisma.user.findFirst();
    const product = await harness.prisma.product.create({
      data: {
        name: "Test Product",
        price: 99.99,
        stock: 1, // Only 1 in stock
      },
    });

    const orderData = {
      userId: user!.id,
      items: [
        {
          productId: product.id,
          quantity: 10, // Requesting more than available
          price: product.price,
        },
      ],
    };

    // Act
    await request(app).post("/api/orders").send(orderData).expect(400);

    // Assert - verify rollback
    const orders = await harness.prisma.order.findMany();
    expect(orders).toHaveLength(0);

    // Verify stock unchanged
    const unchangedProduct = await harness.prisma.product.findUnique({
      where: { id: product.id },
    });
    expect(unchangedProduct!.stock).toBe(1);
  });
});
```

## Authentication Tests

```typescript
// tests/integration/auth.test.ts
describe("Authentication", () => {
  describe("POST /api/auth/login", () => {
    it("should login with valid credentials", async () => {
      // Arrange
      await harness.prisma.user.create({
        data: {
          email: "[email protected]",
          password: await hash("password123"),
        },
      });

      // Act
      const response = await request(app)
        .post("/api/auth/login")
        .send({
          email: "[email protected]",
          password: "password123",
        })
        .expect(200);

      // Assert
      expect(response.body.token).toBeDefined();
      expect(response.body.user.email).toBe("[email protected]");
    });

    it("should reject invalid password", async () => {
      // Act
      const response = await request(app)
        .post("/api/auth/login")
        .send({
          email: "[email protected]",
          password: "wrong-password",
        })
        .expect(401);

      // Assert
      expect(response.body.error).toContain("Invalid credentials");
    });
  });

  describe("Protected routes", () => {
    let authToken: string;

    beforeEach(async () => {
      // Login to get token
      const response = await request(app).post("/api/auth/login").send({
        email: "[email protected]",
        password: "password123",
      });

      authToken = response.body.token;
    });

    it("should access protected route with valid token", async () => {
      await request(app)
        .get("/api/profile")
        .set("Authorization", `Bearer ${authToken}`)
        .expect(200);
    });

    it("should reject request without token", async () => {
      await request(app).get("/api/profile").expect(401);
    });

    it("should reject request with invalid token", async () => {
      await request(app)
        .get("/api/profile")
        .set("Authorization", "Bearer invalid-token")
        .expect(401);
    });
  });
});
```

## Fixtures Management

```typescript
// tests/fixtures/users.ts
export const userFixtures = {
  admin: {
    email: "[email protected]",
    name: "Admin User",
    role: "ADMIN",
  },
  regularUser: {
    email: "[email protected]",
    name: "Regular User",
    role: "USER",
  },
  testUser: {
    email: "[email protected]",
    name: "Test User",
    role: "USER",
  },
};

// tests/fixtures/products.ts
export const productFixtures = {
  laptop: {
    name: "MacBook Pro",
    price: 2499.99,
    stock: 10,
    category: "Electronics",
  },
  phone: {
    name: "iPhone 15",
    price: 999.99,
    stock: 50,
    category: "Electronics",
  },
};

// Usage in tests
await harness.prisma.user.create({
  data: userFixtures.admin,
});
```

## CI-Friendly Strategy

```yaml
# .github/workflows/integration-tests.yml
name: Integration Tests

on: [push, pull_request]

services:
  postgres:
    image: postgres:15
    env:
      POSTGRES_USER: test
      POSTGRES_PASSWORD: test
      POSTGRES_DB: test_db
    ports:
      - 5432:5432
    options: >-
      --health-cmd pg_isready
      --health-interval 10s
      --health-timeout 5s
      --health-retries 5

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - run: npm ci

      - name: Run migrations
        run: npx prisma migrate deploy
        env:
          DATABASE_URL: postgresql://test:test@localhost:5432/test_db

      - name: Run integration tests
        run: npm run test:integration
        env:
          DATABASE_URL: postgresql://test:test@localhost:5432/test_db
```

## Parallel Test Execution

```typescript
// vitest.config.ts
export default defineConfig({
  test: {
    pool: "forks",
    poolOptions: {
      forks: {
        singleFork: false, // Run tests in parallel
      },
    },
    isolate: true, // Isolate each test file
    setupFiles: ["./tests/setup/global-setup.ts"],
  },
});

// Ensure each test file uses separate database
const TEST_DB_PREFIX = "test_db_";

function getDatabaseUrl(): string {
  const workerId = process.env.VITEST_WORKER_ID || "1";
  return `postgresql://test:test@localhost:5432/${TEST_DB_PREFIX}${workerId}`;
}
```

## Best Practices

1. **Isolated tests**: Each test can run independently
2. **Clean state**: Clear database between tests
3. **Fast fixtures**: Minimal data seeding
4. **Transactions**: Test rollbacks explicitly
5. **Real database**: Don't mock database in integration tests
6. **CI-ready**: Use Docker containers
7. **Parallel execution**: Independent test databases

## Output Checklist

- [ ] Test harness created
- [ ] Database setup/teardown
- [ ] Fixture management
- [ ] API endpoint tests
- [ ] Database transaction tests
- [ ] Authentication tests
- [ ] Error case coverage
- [ ] CI workflow configured
- [ ] Parallel execution support
- [ ] Clear test naming

© patricio0312rev · MIT · patricio0312rev/skills

Similar skills

All skills for Testing and QA →
132-java-testing-integration-testing Juan Antonio Breña Moral 132-java-testing-integration-testing is a Claude Code skill that sets up and improves Java integration tests with WireMock. It generates BaseIntegrationTest and JSON mappings. CX Codex +1 401installs acceptance-test-generator shinpr acceptance-test-generator — a subagent for Claude Code generates integration and E2E test skeletons from Design Doc acceptance criteria. Triggers when planning test suites or on requests mentioning test skeletons. CX Codex ★ 720repo stars integration-testing aj-geddes integration-testing helps design and implement integration tests for APIs, databases, message queues, and external services. Useful for validating end-to-end interactions between system components. CX Codex +1 564installs gui-integration-test dominikmartn gui-integration-test is a Claude Code skill that writes and debugs integration tests for Warp's GUI desktop app on the Builder/TestStep harness. Runs when a test is added or fixed. CX Codex +1 ★ 720repo stars integration-test-reviewer shinpr integration-test-reviewer reviews changed integration and E2E tests to see whether they actually prove the claim behind them. Returns the gaps that matter and the smallest fix for each. CX Codex ★ 720repo stars planning-oracle-to-postgres-migration-integration-testing official github planning-oracle-to-postgres-migration-integration-testing is a GitHub Copilot skill that plans integration tests for .NET projects moving from Oracle to PostgreSQL. It finds database access points and ranks them by migration risk. CX Codex +1 1,800installs

From the same set148

The whole set →
react-hook-builder react-hook-builder generates production-grade custom React hooks in TypeScript for data fetching, forms, and local storage. CX Codex +1 269installs mcp-server-builder mcp-server-builder is a Claude Code skill for building MCP servers with tools, resources, and prompts. It activates on requests for an MCP integration or custom Claude tools. CX Codex +1 269installs error-handling-standardizer error-handling-standardizer is a skill that standardizes application errors across custom classes, HTTP responses, and structured logs for consistent API exception handling. CX Codex +1 269installs tech-debt-prioritizer The tech-debt-prioritizer skill scores technical debt by impact, risk, and effort, then ranks the work. Use it to decide which codebase issues to tackle first. CX Codex +1 268installs tanstack-query-setup tanstack-query-setup sets up TanStack Query in a React app: a QueryClient provider, fetch hooks, mutations and cache rules. The agent gets templates it can fill with your code. CX Codex +1 267installs hot-reload-optimizer The hot-reload-optimizer skill for Claude Code fine-tunes hot module replacement and fast refresh in Vite, Next.js, and webpack projects when local rebuilds lag. CX Codex +1 267installs alerting-dashboard-builder alerting-dashboard-builder turns your service level objectives into Prometheus burn-rate alerts and a dashboard template, with runbook links and a first-response guide. CX Codex +1 266installs contract-testing-builder contract-testing-builder implements API contract testing with Pact, OpenAPI, and JSON Schema to catch breaking changes before deploying services. CX Codex +1 266installs

Project sponsors

Companies that keep this analytics open