write-tests
Skill574 starsChanged 14 days agoBSD-3-ClauseView on GitHub
Write Swift unit tests using Swift Testing (the modern Apple testing framework, not XCTest). Use this skill whenever the user asks to write tests, add test cases, create a test suite, or test a Swift type or function. Also triggers when the user asks to convert XCTest tests to Swift Testing, or when adding new tests to an existing XCTest-based file (always convert first). Invoke proactively when the user has just written a new Swift type or function and hasn't tested it yet.
We split this skill into the rules it gives an agent
17 rules. 0 are common, 6 are distinctive, and 11 are very specific to this project.
0
Common
Most of the 65 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Write idiomatic Swift unit tests using Swift Testing.
- Distinctive: line 16
If the user asks to add tests to an existing XCTest file, convert the whole file to Swift Testing first, then add the new tests.
- Very specific: line 37
Never use
// MARK:inside a test suite type: Use a nested struct instead. - Very specific: line 66
Add @Suite to attach a trait (.serialized, .disabled("reason")), or to give a nested suite a display name which reads as a sentence with …
- Distinctive: line 92
When each case of a parameterized test holds more than one value, declare a dedicated struct nested in the suite instead of using a tuple.
- Distinctive: line 148
Use the same style for the whole file: either function names only, or sentences for every nested suite and test.
- Very specific: line 172
Use init / deinit instead of setUp/tearDown.
- Very specific: line 188
Wait for an event, never for a duration.
- Distinctive: line 190
Don't write a test which passes by letting a wait expire, to prove that something did not happen.
- Very specific: line 191
Don't block a thread of the cooperative pool (Thread.sleep, DispatchSemaphore.wait).
- Very specific: line 192
Don't expect a value which depends on scheduling, such as the exact number of tasks running at once.
- Very specific: line 212
Remove : XCTestCase, change class → struct
- Very specific: line 213
Remove test prefix from all method names
- Very specific: line 216
Remove continueAfterFailure = false — use try #require(...) where needed
- Very specific: line 241
Do not keep any @Suite("...") on the top-level struct — struct URLTests needs no annotation.
- Very specific: line 247
Never use static helpers inside a test suite.
- Distinctive: line 268
No sleep, short timeout or expectation which depends on scheduling?
“Common” is measured: kept by at least 6 in 10 of the 65 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Write Tests
Write idiomatic Swift unit tests using Swift Testing.
Non-negotiable: always Swift Testing
Do not write XCTest.
Even when the user doesn't mention a framework, use Swift Testing. XCTest is legacy. The only exception is UI tests, which still require XCTest.
If the user asks to add tests to an existing XCTest file, convert the whole file to Swift Testing first, then add the new tests.
A correct file always looks like this:
import Testing
struct FooTests {
struct Something {
@Test func returnsHelloWorld() {
let foo = Foo()
#expect(foo.something() == "Hello world")
}
}
}Suite structure
Organize tests in nested struct types. Each top-level suite covers one tested type.
Never use // MARK: inside a test suite type. Use a nested struct instead. A // MARK: at file scope (to label a helpers section at the bottom) is the only acceptable use.
// ✅ Correct — nested struct for organization
struct URLTests {
struct Absolute {
@Test func isUnchanged() { ... }
@Test func withFragment() { ... }
}
struct Relative {
@Test func resolution() { ... }
@Test func withDotDot() { ... }
}
}
// ❌ Wrong — MARK inside a suite type
struct URLTests {
// MARK: - Absolute ← must become `struct Absolute { ... }`
@Test func isUnchanged() { ... }
// MARK: - Relative ← must become `struct Relative { ... }`
@Test func resolution() { ... }
}@Suite annotation rules:
- Omit
@Suiteentirely when the struct name already makes the suite's purpose clear. Swift Testing discovers it automatically. - Add
@Suiteto attach a trait (.serialized,.disabled("reason")), or to give a nested suite a display name which reads as a sentence with the ones of its tests (see Display names). - A top-level suite never needs a display name:
URLTestsdoes not need@Suite.LocatorTestsdoes not need@Suite. Just writestruct URLTests {.
Naming:
- Top-level suite:
<TypeName>Tests(e.g.LocatorTests,URLTests) - Nested suites: concept/API name only, no
Testssuffix (e.g.Absolute,Relative,Combining,ErrorHandling)
Declaring tests
// Basic
@Test func returnsNilForInvalidInput() { ... }
// Custom display name — see "Display names" below
@Test("Parsing a locator with a fragment") func parseWithFragment() { ... }
// Parameterized — use instead of copying the same test body multiple times
@Test("All formats round-trip", arguments: Format.allCases)
func roundTrip(format: Format) throws { ... }
// Async/throws — just mark the function
@Test func fetchMetadata() async throws { ... }Arguments with several values
When each case of a parameterized test holds more than one value, declare a dedicated struct nested in the suite instead of using a tuple. Named fields don't need a comment to explain their order, and default values keep the cases short.
The struct is Sendable. Give it a name and conform it to CustomTestStringConvertible, so that the test report shows the name of each case.
// ✅ Correct — a struct with named fields
struct LocatorPosition: Sendable, CustomTestStringConvertible {
let name: String
var durations: [TimeInterval?] = [600, 300, 900]
let locations: Locator.Locations
let expected: TimelinePosition
var testDescription: String { name }
}
@Test(arguments: [
LocatorPosition(
name: "a progression with a known duration",
locations: .init(progression: 0.5),
expected: position(1, 150)
),
LocatorPosition(
name: "a progression with an unknown duration",
durations: [600, nil, 900],
locations: .init(progression: 0.5),
expected: position(1, 0)
),
])
func locatorIsTurnedIntoAPosition(_ example: LocatorPosition) { ... }
// ❌ Wrong — a tuple whose values are only told apart by their position
@Test(arguments: [
([600, 300, 900], Locator.Locations(progression: 0.5), position(1, 150)),
([600, nil, 900], Locator.Locations(progression: 0.5), position(1, 0)),
] as [([TimeInterval?], Locator.Locations, TimelinePosition)])
func locatorIsTurnedIntoAPosition(durations: [TimeInterval?], locations: Locator.Locations, expected: TimelinePosition) { ... }A case holding a single value stays a plain argument, e.g. @Test(arguments: [0, -1]).
Display names
A function name is enough for a simple test. When the behavior needs a sentence to be described, give display names to the nested suite and its tests, so that they read as one sentence in the test report. The suite names the subject and each test continues it, starting with a lowercase letter.
struct ResourceAssetLoaderTests {
@Suite("Invalidating the loader") struct Invalidation {
@Test("returns once the in-flight streams have stopped")
func stopsStreams() async throws { ... }
@Test("refuses the requests which follow, without resolving them")
func refusesRequests() async throws { ... }
}
}Use the same style for the whole file: either function names only, or sentences for every nested suite and test.
Assertions
| Goal | Use |
| Verify a condition (continue on failure) | #expect(condition) |
| Verify and halt on failure | try #require(condition) |
| Unwrap an optional or halt | let x = try #require(optional) |
| Expect a thrown error | #expect(throws: MyError.self) { try ... } |
| Unconditional failure | Issue.record("reason") |
Use force unwrap (!) for values that must exist — don't use guard ... else { return }. A crash on force unwrap produces a clear failure with a line number. A silent return makes the test pass incorrectly when a value is nil.
// ✅ Good
let url = URL(string: "https://example.com")!
// ❌ Bad — silently passes if url is nil
guard let url = URL(string: input) else { return }Setup and teardown
Use init / deinit instead of setUp/tearDown. Each test method gets a fresh instance of the suite struct, so init is sufficient.
struct DatabaseTests {
let db: Database
init() async throws {
db = try await Database.makeInMemory()
}
}Waiting for asynchronous events
Tests run in parallel on CI runners with few cores, which can freeze for more than a minute. A test which depends on timing fails there, even when it passes locally every time.
- Wait for an event, never for a duration. Don't
Task.sleepand hope the work is done. Use anAsyncStreamwithfirst(within:)fromTestSupport, orconfirmation(...). - A timeout only exists to fail a broken test instead of hanging. Use
TimeInterval.testTimeoutfromTestSupport, never a few seconds. - Don't write a test which passes by letting a wait expire, to prove that something did not happen. Wait for a later event instead, then check the state.
- Don't block a thread of the cooperative pool (
Thread.sleep,DispatchSemaphore.wait). When a test must hold a thread, run that part on its own dispatch queue. - Don't expect a value which depends on scheduling, such as the exact number of tasks running at once. Expect a bound (
<= 3), or gate the tasks so the test controls the order.
// ✅ Good — waits for the event, the timeout is only reached on failure
let (events, continuation) = AsyncStream<Event>.makeStream()
sut.onEvent = { continuation.yield($0) }
sut.start()
#expect(await events.first(within: .testTimeout, where: { $0 == .started }) != nil)
// ❌ Bad — fails on a busy runner
sut.start()
try await Task.sleep(nanoseconds: 500_000_000)
#expect(sut.isStarted)Converting from XCTest — step by step
Given an XCTest file, apply these transformations in order:
- Replace
import XCTest→import Testing - Remove
: XCTestCase, changeclass→struct - Remove
testprefix from all method names - Replace
setUpWithError()→init() throws,tearDownWithError()→deinit(on a class/actor) - Replace assertions:
XCTAssertEqual(a, b)→#expect(a == b),XCTAssertNil(x)→#expect(x == nil),XCTUnwrap(x)→try #require(x),XCTFail("msg")→Issue.record("msg") - Remove
continueAfterFailure = false— usetry #require(...)where needed - Convert every
// MARK:group inside the type into a nested struct:
// Before (XCTest)
final class URLTests: XCTestCase {
// MARK: - Absolute
func testAbsoluteURLIsUnchanged() { XCTAssertEqual(...) }
// MARK: - Relative
func testRelativeURLResolution() { XCTAssertEqual(...) }
}
// After (Swift Testing)
struct URLTests {
struct Absolute {
@Test func absoluteURLIsUnchanged() { #expect(...) }
}
struct Relative {
@Test func relativeURLResolution() { #expect(...) }
}
}Do not keep any @Suite("...") on the top-level struct — struct URLTests needs no annotation.
Helpers
- Single-suite helpers:
fileprivatefunctions at the bottom of the file. A// MARK: - Helpersat file scope (outside any suite type) is acceptable. - Cross-suite helpers:
internalfree functions in a dedicatedTestHelpers.swiftfile in the test target, or in their own files for mocks/fakes. - Never use
statichelpers inside a test suite.
// At file scope, after all suite types
// MARK: - Helpers
fileprivate func makeLocator(href: String = "/ch.html", progression: Double? = nil) -> Locator {
Locator(href: href, type: "text/html", locations: .init(progression: progression))
}Review checklist (fix before presenting)
- Does every file start with
import Testing? Zeroimport XCTest. - Happy path, boundary conditions, and error cases covered?
- Similar tests collapsed into
@Test(arguments:)parameterized tests, with a struct when a case holds several values? - No
// MARK:inside any suite type? - No
@Suitewithout a trait or a display name reading as a sentence with its tests? - No
guard ... else { return }— replaced with!ortry #require? - Three or more tests sharing setup? Extract a
fileprivatehelper. - No sleep, short timeout or expectation which depends on scheduling?
Traits and advanced features
.serialized: run a suite's tests sequentially (use only when tests share mutable state).disabled("reason"): skip a test with a documented reason@Test(.tags(.networking)): tag for CI filteringconfirmation(...): for callback-based async events#expect(processExitsWith: .failure) { ... }: for testingprecondition/fatalError
Other versions69 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 69
- remix-run/remix★ 33ksame name
- elie222/inbox-zero★ 13ksame name
- getsentry/sentry-javascript★ 8.8ksame name
- dzhng/jevgrep★ 3.1ksame name
- meta-pytorch/OpenEnv★ 2.8ksame name
- huggingface/OpenEnv★ 2.8ksame name
- JamieMason/syncpack★ 2.1ksame name
- dzhng/skills★ 1.4ksame name
- clice-io/clice★ 1.4ksame name
- ryokun6/ryos★ 1.3ksame name
59 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use close-spec, design-with-images and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
dzhngSkillclose-spec
When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).
Also in 5 projects that use this
dzhngSkilldesign-with-images
Explore UI and visual design with image generation, then iterate the real implementation against the user-selected concept. Use when brainstorming visual directions, offering mockup variants, or implementing an approved generated design; do not stop at the mockups or the first code approximation.
Also in 5 projects that use this
transitive-bullshitSkillcompare-screenshots
Compare screenshots against the intended design, distinguishing approved references from historical baselines. Use for iterative implementation matching, before/after visual review, objective image telemetry, or checking a lone capture for flat, empty, or badly framed content.
Also in 5 projects that use this
LucasMatuszewskiSkillaudit-agents
Audit and maintain agent configuration files (.claude/agents, AGENTS.md, CLAUDE.md, agent-memory). Checks for duplicates, outdated info, naming conflicts, wrong technical facts, and files over 200 lines. Fixes all issues and commits.
Also in 5 projects that use this
wolverin0Skillaudit-decisions
Standardize remediation decisions, baseline-policy entries, and legal-review banners for accepted, deferred, or policy-blocked audit findings.
Also in 4 projects that use this
rhnfzlSkillexplore-unknowns
Walk the user through mapping the unknowns of a task before, during, and after they build it, and hand them a four-quadrant map (settled ground, open decisions, taste, and landmines) they keep. Reach for this eagerly whenever a request is ambiguous or underspecified, the codebase or domain is unfamiliar, the user will "know it when they see it", a reference implementation must be understood before porting, a build-queue or architecture-changing task is about to start, a mid-build deviation needs capturing, or a finished change needs buy-in or verified understanding before merge. Trigger even when the skill is not named: "do a blindspot pass", "find my unknown unknowns", "interview me about this change", "brainstorm the approach for a task I am about to build", "help me scope this", "what am I missing here", "plan this before I build", "I know nothing about X in this codebase". When a territory profile is present it reads memory and the graph first and feeds the map into the build pipeline; without one it degrades to a plain general map. Not for trivial or mechanical tasks with clear acceptance criteria, single-fact lookups, pure debugging of a known symptom, or pure code review, those have their own tools. Do not use it to run the build itself; the map is the deliverable and implementation remains a separate task, whether it has not started or is already underway.
Also in 5 projects that use this
- +5 more from dzhng
In this repository4 other files it gives its agents.
- AGENTS.mdAGENTS.md
- update-changelogSkill
- write-guideSkill
- write-release-announcementSkill
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.

