Course contentsShow
← Rust
Lesson 1649 of 1,91014. System Integration and EcosystemFree lesson

Document Testing

You will ensure all technical examples in your code documentation remain functional through doc-testing.

In this lesson, you will learn how to turn your documentation comments into a living test suite that ensures your API examples never drift from your actual code.

The Power of Doctests

In Rust, the line between documentation and verification is intentionally blurred. By using triple-slash (///) comments, you can write Markdown-formatted documentation that includes code blocks. When you run cargo test, Rust automatically extracts these blocks, compiles them, and executes them as unit tests. This guarantees that your documentation is always accurate and your examples remain functional as your codebase evolves.

Anatomy of a Documentation Test

Consider a simple utility function in your library. When you write a doc-comment for it, you can include a snippet that demonstrates how to use the function:

/// Adds two integers together.
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

When you run cargo test, Rust treats the code block inside that doc-comment as a standalone integration test. If you rename add to sum in your library but forget to update the documentation, the test will fail during compilation, alerting you immediately to the drift.

Advanced Doctest Control

Sometimes you need to write example code that isn't intended to be executed, or that requires specific setup. You can use doc-test attributes to manage this:

  • no_run: The code is compiled to ensure it’s valid, but it is not executed. Useful for code that performs IO or requires long-running processes.
  • ignore: Prevents the test from running, though it is still checked for syntax.
  • should_panic: Used when you want to verify that an example correctly triggers a panic.
/// ```should_panic
/// my_crate::risky_operation();
/// ```
pub fn risky_operation() { panic!("Oh no!"); }

By integrating these tests directly into your documentation, you eliminate the "stale example" problem, providing your users with documentation they can trust and reducing the manual effort required to keep your API guides synchronized with your implementation.

Key Takeaway: Documentation tests turn your API examples into compile-time guarantees, ensuring that your public-facing documentation remains accurate and functional as your code changes.