Skip to main content
rule CX Codex

rust-tests — Claude Code rule: Rust tests and installation

This rule sets conventions for Rust tests, from module placement and naming to fixtures and HTTP mocks. Use it when you want tests in a project to follow the same structure.

MIT ★ 1,627 updated 2026-10-25

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/rust-tests.instructions.md
Open on GitHub

What rust-tests does

Keep unit tests beside the code they exercise, inside #[cfg(test)] mod tests; put integration tests in the crate-root tests/ directory. Test names should describe behavior, and helper functions can provide repeated fixture data. The rule favors one assertion per test, while allowing related checks together.

It points to mockall for trait mocks, wiremock for async HTTP tests, and mockito for HTTP mocking in sync or async tests. Unit tests must stay on loopback: DNS lookups and connections to non-loopback addresses break that constraint. The rule also inherits conventions from rust.instructions.md.

What it helps with

  • place unit tests beside the Rust code they cover
  • name tests to describe the expected behavior
  • keep HTTP tests off external networks
  • reuse fixture helpers for repeated test data
  • move integration tests into the crate-root tests/ directory

Example prompts for the agent

  • Add Rust tests for this module following the rust-tests rule.
  • Check that this HTTP test uses a local mock and makes no external network calls.
  • Move the integration tests into the crate-root tests/ directory and rename them to describe their behavior.

How to install rust-tests

Manually: put the files in place

.github/instructions/rust-tests.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about rust-tests

How do I install rust-tests in Claude Code?

Copy the rule file to .claude/rules/rust-tests.md.

What does rust-tests do?

It defines conventions for Rust test placement, naming, fixtures, and HTTP mocks. It also requires unit tests to avoid external network access.

Which mocking libraries does rust-tests cover?

It recommends mockall for trait-based mocks, wiremock for async HTTP tests, and lists mockito for HTTP mocking in synchronous or asynchronous tests.

Source text

rust-tests.instructions.md · MIT
---
applyTo: '**/*.rs'
description: 'Rust test code authoring conventions'
---

# Rust Test Instructions

Conventions for Rust test code. All conventions from [rust.instructions.md](rust.instructions.md) apply, including naming, error handling, and module structure.

## Test Module Placement

Place unit tests in `#[cfg(test)] mod tests` within the source file they exercise:

<!-- <example-tests> -->
```rust
#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn given_valid_input_parse_returns_config() {
        let json = r#"{"endpoint": "http://127.0.0.1"}"#;
        let config: AppConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.polling_interval_secs, 10);
    }

    #[tokio::test]
    async fn when_endpoint_available_fetch_returns_data() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"data"))
            .mount(&mock_server)
            .await;

        let config = AppConfig {
            endpoint: mock_server.uri(),
            polling_interval_secs: 10,
        };
        let service = PollingService::new(config);
        let result = service.fetch().await;
        assert!(result.is_ok(), "fetch should succeed when the mock endpoint is available");
    }
}
```
<!-- </example-tests> -->

## Test Naming

Test method format: `given_context_when_action_then_expected` or descriptive snake_case that reads as a behavior statement.

```text
given_valid_input_parse_returns_config
when_endpoint_unavailable_send_returns_error
parses_empty_payload_as_default
```

Prefer one assertion per test. Related assertions validating the same behavior are acceptable.

## Mocking Libraries

| Library    | Usage                                                   |
|------------|---------------------------------------------------------|
| `mockall`  | Preferred for trait-based mocking                       |
| `wiremock` | HTTP server mocking in async tests                      |
| `mockito`  | Lightweight HTTP mocking for synchronous or async tests |

Keep unit tests network-isolated. Unit tests must not perform DNS resolution or connect to non-loopback addresses. For HTTP behavior, inject a loopback endpoint supplied by `wiremock`, `mockito`, or an equivalent local test double. Tests that require a deployed service belong in a separately controlled integration-test environment.

Use `mockall` to generate mock implementations from traits via `#[automock]`:

```rust
use mockall::automock;

// Application types — defined in your crate (see rust.instructions.md)
pub struct Item {
    pub id: String,
}

// Uses the module-scoped Result alias from rust.instructions.md
#[automock]
pub trait Repository: Send + Sync {
    fn find_by_id(&self, id: &str) -> Result<Option<Item>>;
}

pub struct ItemService {
    repo: Box<dyn Repository>,
}

impl ItemService {
    pub fn new(repo: Box<dyn Repository>) -> Self {
        Self { repo }
    }

    pub fn get(&self, id: &str) -> Result<Option<Item>> {
        self.repo.find_by_id(id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockall::predicate::*;

    #[test]
    fn given_existing_item_service_returns_it() {
        let mut mock = MockRepository::new();
        mock.expect_find_by_id()
            .with(eq("42"))
            .returning(|_| Ok(Some(Item { id: "42".into() })));

        let service = ItemService::new(Box::new(mock));
        let result = service.get("42").unwrap();
        assert_eq!(result.unwrap().id, "42");
    }
}
```

Use `wiremock` to mock HTTP servers in async tests:

```rust
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[tokio::test]
async fn when_api_returns_ok_fetch_succeeds() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"id": "1"}"#))
        .mount(&mock_server)
        .await;

    let client = reqwest::Client::new();
    let response = client.get(mock_server.uri()).send().await.unwrap();
    assert_eq!(response.status(), 200);
}
```

Add test dependencies to `[dev-dependencies]` in `Cargo.toml`:

```toml
[dev-dependencies]
mockall = "0.13"
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["macros", "rt"] }
wiremock = "0.6"
```

## Test Data Patterns

Use builder functions or fixture helpers for test data rather than repeating inline construction:

```rust
#[cfg(test)]
mod tests {
    use super::*;

    fn sample_config() -> AppConfig {
        AppConfig {
            endpoint: "http://127.0.0.1".into(),
            polling_interval_secs: 10,
        }
    }

    #[test]
    fn given_custom_interval_config_uses_override() {
        let config = AppConfig {
            polling_interval_secs: 30,
            ..sample_config()
        };
        assert_eq!(config.polling_interval_secs, 30);
    }
}
```

Inline construction is acceptable for simple one-field tests where a builder adds no clarity.

## Integration Tests

Place integration tests in the `tests/` directory at the crate root. Each file in `tests/` compiles as a separate crate with access to the library's public API only:

```rust
// tests/polling_integration.rs
use my_service::AppConfig;

#[tokio::test]
async fn given_valid_config_service_starts() {
    let config = AppConfig {
        endpoint: "https://example.com".into(),
        polling_interval_secs: 1,
    };
    assert!(!config.endpoint.is_empty());
}
```

## Test Conventions

* Use `#[tokio::test]` for async tests.
* Prefer assertion messages that explain intent: `assert!(result.is_ok(), "should parse valid JSON")`.
* Use builder functions or fixture helpers for test data rather than repeating inline construction.
* Place integration tests in the `tests/` directory at the crate root.

## Complete Example

Types referenced below (`AppConfig`, `ServiceError`, `Result` alias) are defined in [rust.instructions.md](rust.instructions.md).

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Fixture helper — see Test Data Patterns
    fn sample_config(endpoint: String) -> AppConfig {
        AppConfig {
            endpoint,
            polling_interval_secs: 10,
        }
    }

    #[test]
    fn given_defaults_config_has_ten_second_interval() {
        let config = sample_config("http://127.0.0.1".into());
        assert_eq!(config.polling_interval_secs, 10);
    }

    #[test]
    fn service_error_not_found_formats_message() {
        let err = ServiceError::not_found("item 42");
        assert_eq!(err.to_string(), "Not found: item 42");
    }

    #[tokio::test]
    async fn when_api_returns_service_unavailable_fetch_error_contains_status() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(503))
            .mount(&mock_server)
            .await;

        let config = sample_config(mock_server.uri());
        let service = PollingService::new(config);
        let error = service.fetch().await.expect_err("503 response should fail");
        assert!(error.to_string().contains("HTTP 503"), "error should include status");
    }
}
```

© microsoft · MIT · microsoft/hve-core

Similar IDE rules

All IDE rules for Testing and QA →

From the same set148

The whole set →
risk-register Generates a qualitative risk register using a Probability × Impact matrix, assigns owners, defines mitigation strategies, and creates contingency plans. CX Codex +1 ★ 1,627repo stars hve-builder The hve-builder rule sets authoring conventions for prompts, agents, subagents, instructions, and skills. It activates for matching artifact files. CX Codex +1 ★ 1,627repo stars python-tests python-tests sets pytest authoring conventions: AAA test structure, given-when-then naming, and when to reach for mocker, monkeypatch or MagicMock. CX Codex +1 ★ 1,627repo stars vex OpenVEX v0.2.0 reference and management playbooks for structuring, checking, and validating vulnerability statements. CX Codex +1 ★ 1,627repo stars CVE Analyzer CVE Analyzer — a subagent for deep CVE analysis: checks if vulnerable code is reachable in the project and returns evidence-backed VEX status. CX Codex +1 ★ 1,627repo stars python-script python-script defines Python 3.11+ script standards for Claude Code, enforcing package workflows with uv, modern type syntax, and clean CLI structures. CX Codex +1 ★ 1,627repo stars hve-artifact-authoring The hve-artifact-authoring skill guides the creation and validation of HVE Core agents, prompts, instructions, and skills. Use it when preparing an artifact in the repository and checking it against project conventions. CX Codex +1 ★ 1,627repo stars vex-generation The vex-generation rule guides AI-assisted VEX triage with evidence requirements, confidence bands, and status constraints. Use it when an agent drafts vulnerability findings for human review. CX Codex +1 ★ 1,627repo stars

Project sponsors

Companies that keep this analytics open