agentleFS
golid-aigolid-ai/golid/.cursor/rules/write-tests.mdc

golid / rules

Cursor rule40 starsChanged 6 months agoMITView on GitHub

Patterns for writing backend tests — integration tests with TestDB, unit tests for pure logic, test data seeding

The file

We split this write-tests.mdc into the rules it gives an agent

7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Before writing tests for a module,: read docs/modules/{module}/spec.md for the Critical Test Scenarios section — it's a verified test plan.

    line 11
  2. Very specific:

    Test real SQL against a real PostgreSQL instance using testutil.WithTestDB.

    line 16
  3. Very specific:

    Seed with raw SQL: Use pool.Exec with INSERT statements.

    line 49
  4. Distinctive:

    Happy paths: Create, Read, Update, Delete with valid inputs.

    line 55
  5. Very specific:

    Create a mock struct implementing the service interface.

    line 103
  6. Very specific:

    After scaffolding, fill in test bodies for your specific validation rules, error paths, and edge cases.

    line 113
  7. Distinctive:

    Don't just test happy paths.

    line 117

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
write-tests.mdc
---
description: Patterns for writing backend tests — integration tests with TestDB, unit tests for pure logic, test data seeding
globs: backend/**/*_test.go
alwaysApply: false
---

# Writing Backend Tests

> **Thesis:** Test the contract, not the implementation. Integration tests hit real PostgreSQL; unit tests are table-driven; every service method has error path coverage.

**Before writing tests for a module,** read `docs/modules/{module}/spec.md`
for the Critical Test Scenarios section — it's a verified test plan.

## Integration Tests (Service Layer)

Test real SQL against a real PostgreSQL instance using `testutil.WithTestDB`.

```go
//go:build integration

package service_test

import (
    "testing"
    "github.com/golid-ai/golid/backend/internal/service"
    "github.com/golid-ai/golid/backend/internal/testutil"
)

func TestItemService_Create(t *testing.T) {
    testutil.WithTestDB(t, func(pool *pgxpool.Pool) {
        svc := service.NewItemService(pool, 20, 100)

        // Seed prerequisite data with raw SQL
        _, err := pool.Exec(ctx, `INSERT INTO users (...) VALUES (...)`)
        // ...

        // Test the service method
        result, err := svc.Create(ctx, &service.CreateItemInput{...})
        if err != nil { t.Fatalf("expected no error, got %v", err) }
        if result.Title != "Test Item" { t.Errorf("expected title 'Test Item', got %s", result.Title) }
    })
}
```

### Key Rules

- **Build tag**: `//go:build integration` at the top of the file.
- **File naming**: `x_integration_test.go` (not `x_test.go`) to make it clear.
- **Seed with raw SQL**: Use `pool.Exec` with INSERT statements. Never use service methods to seed — they have their own validation and side effects.
- **Test one thing per function**: Each test function should test one behavior (happy path, error case, permission check, etc.).
- **Clean state**: `WithTestDB` provides a fresh database for each test. No cleanup needed.

### What to Test

- **Happy paths**: Create, Read, Update, Delete with valid inputs.
- **Permission checks**: Wrong user type, non-owner, non-member. Expect `FORBIDDEN`.
- **Status guards**: Operation on wrong-status parent. Expect `BAD_REQUEST`.
- **Not found**: Non-existent ID. Expect `NOT_FOUND`.
- **Conflict**: Duplicate entries. Expect `CONFLICT`.
- **Edge cases**: Empty arrays, null optional fields, boundary values.

Reference: existing `_integration_test.go` files in `backend/internal/service/`

## Unit Tests (Pure Logic)

For validation helpers, parsing functions, and other pure logic — no build tag needed.

```go
package pagination

import "testing"

func TestNormalize(t *testing.T) {
    tests := []struct {
        page, perPage   int
        wantP, wantPP   int
    }{
        {0, 0, 1, 20},
        {-1, 200, 1, 20},
        {5, 10, 5, 10},
    }
    for _, tt := range tests {
        p, pp := Normalize(tt.page, tt.perPage, 20, 100)
        if p != tt.wantP || pp != tt.wantPP {
            t.Errorf("Normalize(%d, %d) = (%d, %d), want (%d, %d)",
                tt.page, tt.perPage, p, pp, tt.wantP, tt.wantPP)
        }
    }
}
```

### Key Rules

- **No build tag** — runs on every `go test`.
- **Same package** — test exported functions in their own subpackage (e.g., `pagination.Normalize` lives in `service/pagination/` and is tested in `service/pagination/pagination_test.go`).
- **Table-driven tests** — use `[]struct` pattern for multiple cases.
- **File naming**: `x_test.go` in the same directory as the code.

Reference: existing `_test.go` files in `backend/internal/service/`

## Mock-based Handler Tests

Create a mock struct implementing the service interface. Set function fields for methods under test. Unimplemented methods panic. Inject mock directly into handler struct: `h := &AuthHandler{authService: &mockAuthService{...}}`. See `handler/auth_test.go` for examples.

## Scaffold-Generated Tests

`make new-module name=items` automatically generates `handler/item_test.go` with:

- A `mockItemService` struct implementing the `itemServicer` interface
- A `testItemDetail()` helper returning sample data
- 5 test stubs: Create success, Create validation error, List, GetByID not found, Delete

After scaffolding, fill in test bodies for your specific validation rules, error paths, and edge cases. The generated tests follow the same pattern as `auth_test.go`.

## Always Test Error Paths

Don't just test happy paths. Every service method should have tests for:

- **Permission denied** — wrong user type, non-owner, non-member → expect `FORBIDDEN`
- **Invalid status** — operation on wrong-status entity → expect `BAD_REQUEST`
- **Not found** — non-existent ID → expect `NOT_FOUND`
- **Duplicate/conflict** — re-creating existing entity → expect `CONFLICT`

These are the bugs that slip through manual testing and break in production.

> This section is intentionally duplicated in `write-tests.mdc` and `write-tests-frontend.mdc`. If updated, change both.

## Related Rules

For test planning patterns (discriminator matrix, predicate-derived plans, integration DB safety), see `write-tests-planning`. For frontend component test patterns, see `write-tests-frontend`. For browser/E2E test patterns, see `write-tests-e2e`.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.