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
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- .cursor/rules/audit-bugs.mdcCursor rule
- .cursor/rules/audit-codebase.mdcCursor rule
- .cursor/rules/ci-workflow.mdcCursor rule
- .cursor/rules/codebase-standards.mdcCursor rule
- .cursor/rules/common-commands.mdcCursor rule
- .cursor/rules/deploy-infra.mdcCursor rule
- .cursor/rules/document-module.mdcCursor rule
- .cursor/rules/dynamic-image-endpoints.mdcCursor rule
- .cursor/rules/dynamic-image-http.mdcCursor rule
- .cursor/rules/external-api.mdcCursor rule
- .cursor/rules/feature-flags.mdcCursor rule
- .cursor/rules/frontend-components-advanced.mdcCursor rule
- .cursor/rules/frontend-components.mdcCursor rule
- .cursor/rules/frontend-forms.mdcCursor rule
- .cursor/rules/frontend-lib.mdcCursor rule
- .cursor/rules/git-commits.mdcCursor rule
- .cursor/rules/go-handler.mdcCursor rule
- .cursor/rules/go-service-errors.mdcCursor rule
- .cursor/rules/go-service.mdcCursor rule
- .cursor/rules/iteration-surface.mdcCursor rule
- .cursor/rules/job-queue.mdcCursor rule
- .cursor/rules/observability.mdcCursor rule
- .cursor/rules/openapi.mdcCursor rule
- .cursor/rules/parallel-subagents.mdcCursor rule
- .cursor/rules/plan-execution-loop.mdcCursor rule
- .cursor/rules/plan-feature-execution.mdcCursor rule
- .cursor/rules/plan-feature.mdcCursor rule
- .cursor/rules/plan-infra.mdcCursor rule
- .cursor/rules/planning-standards.mdcCursor rule
- .cursor/rules/refactor-large-files.mdcCursor rule
- .cursor/rules/rename-tool.mdcCursor rule
- .cursor/rules/seed-data.mdcCursor rule
- .cursor/rules/slice-and-ship.mdcCursor rule
- .cursor/rules/solidjs-data-fetching.mdcCursor rule
- .cursor/rules/solidjs-pages.mdcCursor rule
- .cursor/rules/solidstart-routing.mdcCursor rule
- .cursor/rules/sql-migrations.mdcCursor rule
- .cursor/rules/sse-realtime.mdcCursor rule
- .cursor/rules/workflow-routing.mdcCursor rule
- .cursor/rules/write-rules.mdcCursor rule
- .cursor/rules/write-tests-e2e.mdcCursor rule
- .cursor/rules/write-tests-frontend.mdcCursor rule
- .cursor/rules/write-tests-frontend-workflow.mdcCursor rule
- .cursor/rules/write-tests-planning.mdcCursor rule
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
- Very specific: line 11
Before writing tests for a module,: read docs/modules/{module}/spec.md for the Critical Test Scenarios section — it's a verified test plan.
- Very specific: line 16
Test real SQL against a real PostgreSQL instance using testutil.WithTestDB.
- Very specific: line 49
Seed with raw SQL: Use pool.Exec with INSERT statements.
- Distinctive: line 55
Happy paths: Create, Read, Update, Delete with valid inputs.
- Very specific: line 103
Create a mock struct implementing the service interface.
- Very specific: line 113
After scaffolding, fill in test bodies for your specific validation rules, error paths, and edge cases.
- Distinctive: line 117
Don't just test happy paths.
≈ “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.
Files
---
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`.
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
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.

