rust-write-tests
БесплатноБез исполняемых скриптовНе проверенExpert-level Rust testing — the "What Could Break?" framework, five transformations from superficial to expert tests, flake hunting protocol, intent-based…
от pproenca★ 231 звезда на GitHubОб этом скилле
Rust Test Writing Skill
Write tests that catch real bugs. Every test must guard a specific invariant -- not just prove the code "works."
The "What Could Break?" Framework
Before writing any test, answer these four questions:
- What invariant does this code maintain? (e.g., "deserialized config always has a default profile")
- What edge case would violate it? (e.g., "empty TOML table, missing key, extra unknown key")
- What platform difference could surface? (e.g., "path separators, case sensitivity, symlink behavior")
- What would a future refactor accidentally break? (e.g., "field added to struct but not to Display impl")
If you can only answer #1, your test is a happy-path test. Answer all four and you have a regression suite.
The 5 Test Transformations
Each transformation shows a superficial test pattern and its expert replacement.
Transformation 1: Weak assertions -> whole-object comparison
// BEFORE: proves nothing about the rest of the struct
let result = parse_config(input)?;
assert!(result.is_ok());
// AFTER: catches any unexpected field change
use pretty_assertions::assert_eq;
let result = parse_config(input)?;
assert_eq!(result, Config {
name: "default".into(),
timeout: Duration::from_secs(30),
retries: 3,
verbose: false,
});
Transformation 2: Single happy-path -> targeted test suite
// BEFORE: one test, one path
#[test]
fn test_parse_config() {
let cfg = parse("valid input").unwrap();
assert!(cfg.is_valid());
}
// AFTER: 3-6 tests covering happy, error, edge, platform
#[test]
fn parse_config_returns_defaults_for_minimal_input() { .. }
#[test]
fn parse_config_rejects_negative_timeout() { .. }
#[test]
fn parse_config_preserves_unknown_fields_as_extensions() { .. }
#[test]
fn parse_config_handles_empty_string_gracefully() { .. }
#[cfg(windows)]
#[test]
fn parse_config_normalizes_backslash_paths() { .. }
Transformation 3: Inline test module -> sibling _tests.rs file
// BEFORE: tests pollute the production file diff
// foo.rs
pub fn compute() -> u32 { 42 }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() { assert_eq!(compute(), 42); }
}
// AFTER: production code and test code in sibling files
// foo.rs
pub fn compute() -> u32 { 42 }
#[cfg(test)]
#[path = "foo_tests.rs"]
mod tests;
// foo_tests.rs
use super::*;
#[test]
fn compute_returns_expected_value() { assert_eq!(compute(), 42); }
For mod.rs modules, use mod_tests.rs.
Transformation 4: String-based test data -> typed struct construction
// BEFORE: silent breakage when fields change
let input: Config = serde_json::from_str(r#"{"name":"test","timeout":30}"#)?;
// AFTER: compile-time safety for field additions/renames
fn make_config(name: &str, timeout_secs: u64) -> Config {
Config {
name: name.to_string(),
timeout: Duration::from_secs(timeout_secs),
retries: 0,
verbose: false,
}
}
let input = make_config("test", 30);
Factory functions for domain objects let each test construct exactly the fixture it needs. No shared mutable state. No JSON parsing at test time.
Transformation 5: HashMap in fixtures -> BTreeMap for determinism
// BEFORE: test passes 99% of the time, flakes in CI
let mut map = HashMap::new();
map.insert("b", 2);
map.insert("a", 1);
assert_eq!(format!("{map:?}"), r#"{"a": 1, "b": 2}"#); // order not guaranteed
// AFTER: deterministic iteration order
let mut map = BTreeMap::new();
map.insert("b", 2);
map.insert("a", 1);
assert_eq!(format!("{map:?}"), r#"{"a": 1, "b": 2}"#); // always this order
Use BTreeMap whenever output order affects assertions or snapshots.
Test Flake Hunting Protocol
Bolin's single most frequent pattern (97+ references across 30+ commits). When a test is flaky, follow this exact protocol:
- Identify the race window -- read the event-emission code, find where timing assumptions break. Locate the exact line where the test assumes an event has arrived or a state has changed without proof.
- Replace timing with event-driven sync -- wait for a specific event instead of sleeping or assuming order. Never use
sleepas a synchronization primitive. - Make assertions order-independent -- sort collected values, use sets, or match by content not position. Non-deterministic event ordering is not a bug; asserting on it is.
- Stress-test the fix -- run with the exact command:
cargo nextest run -p <crate> -j 2 --no-fail-fast --stress-count 50 --status-level leak - Document the non-determinism in the commit message -- explain why the timing assumption was wrong and what synchronization replaced it.
// BEFORE (timing-dependent):
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(events.len(), 2);
assert_eq!(events[0].type_name, "item.create");
assert_eq!(events[1].type_name, "audio.delta");
// AFTER (event-driven, order-independent):
wait_for_event
Установить rust-write-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл rust-write-tests?
Expert-level Rust testing — the "What Could Break?" framework, five transformations from superficial to expert tests, flake hunting protocol, intent-based assertions, naming conventions, and a mandatory self-review checklist. Triggers on writing Rust tests, designing test cases, improving test quality, or reviewing test coverage.
Как установить скилл rust-write-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rust-write-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic