Sub topic 10
How rustdoc compiles and runs doc tests
This chapter assumes you can write /// comments, put fenced code blocks in them, and run cargo test --doc. Here you will learn what happens between that command and the pass or fail line. That knowledge explains most surprising doc test failures.
The model: one example, one program
cargo test --doc does not run your doc tests inside your library's test binary. It calls rustdoc --test, and rustdoc does this:
- It parses your crate's source and collects every doc comment, including those on private items.
- It extracts each fenced code block that counts as Rust code.
- It turns each block into a small standalone program.
- It compiles that program with your library as an external dependency.
- It runs the executable and reports the result.
Your library is built once, normally, and each example links against it like any other crate would. The consequences:
- Examples can use only the public API. A
pub(crate)or private function is not visible to a doc test. - Examples share no state. Each one has its own
main, its own statics, and its own process. - A compile error is a failure, and so is a panic or a non-zero exit code.
- A failing example does not stop the others. rustdoc reports all of them.
What rustdoc generates from your block
Look at the example from the add function:
/// Adds two numbers.
///
/// ```
/// use mycrate::add;
///
/// assert_eq!(add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}The block has no fn main, so rustdoc wraps the whole body in one. The generated program is roughly:
#![allow(unused)]
fn main() {
let v = vec![1, 2, 3];
assert_eq!(v.len(), 3);
}This is a simplified sketch with std-only code. For the real add test, the body is the two lines from the comment, and rustdoc also makes your crate available under its own name.
The rules for building the program are:
- Wrapping in
main. If the example definesfn main, rustdoc leaves it alone. Otherwise it puts all the code inside a generatedfn main() { ... }. - Crate attributes are hoisted. Lines like
#![allow(dead_code)]are moved outsidemain, because they are only valid at the top of a crate. - Unused warnings are off. rustdoc adds
#![allow(unused)]by default, so an example that builds a value and never reads it still compiles quietly. - Your crate is linked in. rustdoc inserts an
extern crateline for your library when the example needs it. You still writeuse mycrate::add;yourself, or you can callmycrate::add(...)directly. - Hidden lines are included. Lines that start with
#are part of the generated program. They are only removed from the rendered HTML. - The edition matches your crate. The program is compiled with the
editionfrom yourCargo.toml, soasyncand other edition-dependent syntax behave the same as in your library.
Items you define in an example, such as a struct or a helper fn, end up inside the generated main. They are local to that test. If the example defines its own fn main, put your helper items beside it and rustdoc will not wrap anything.
Seeing it run
Running the doc tests prints one line per example. The name contains the file and the line where the code block starts:
cargo test --docrunning 3 tests
test src/lib.rs - add (line 5) ... ok
test src/lib.rs - divide (line 24) - should panic ... ok
test src/lib.rs - parse_port (line 41) ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.61sThe line number points at the opening fence of the block in your source, which makes failures easy to find. When a test fails, rustdoc prints the compiler error or panic message together with the generated source, so you can see exactly what it compiled.
You can filter by name, in the same way as for ordinary tests:
cargo test --doc parse_portA word of caution on timing. Every non-merged example is a separate compile and link step. A crate with several hundred examples can take noticeably longer to test than its unit tests. Marking an example no_run skips only the execution, so it still pays the compile cost.
Visibility and what examples can reach
Because the example is an external crate, it follows the same privacy rules as your users. This holds even for doc comments on private items, which rustdoc still extracts and tests. Their examples must also go through the public API.
You can use that fact to document the boundary with a test:
fn helper() -> i32 {
1
}
/// Returns the answer.
///
/// Private items are not reachable from a doc test:
///
/// ```compile_fail
/// mycrate::helper();
/// ```
pub fn answer() -> i32 {
helper() + 41
}The compile_fail example passes because the compiler rejects the call to the private helper. Be careful with this attribute. It passes for any compile error, including a typo, so it does not prove that the privacy rule is the cause.
Two other points about the environment:
- Dependencies. Examples can use your
[dependencies]and your[dev-dependencies]. A crate that is only a dev-dependency is still usable in a doc test, even though it is not available to users of your library. - Binary crates. Doc tests only run for library targets. A package that has only
src/main.rshas nothing forcargo test --docto test. Move shared logic intosrc/lib.rsif you want tested examples.
`cfg(test)` and `cfg(doctest)`
The library is compiled normally for doc tests, not in test mode. So #[cfg(test)] code does not exist, and an example cannot call a function that is gated with it.
rustdoc does set a separate flag, cfg(doctest), while it collects doc tests. This lets you attach extra documentation that should only be tested. The standard use is to test a README:
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;The struct exists only during doc test collection. It is never part of the real build, so it does not show up in your public API. Every Rust code block in README.md now runs as a doc test, which keeps the README from going stale.
Which blocks count as tests
rustdoc treats a code block as Rust unless you say otherwise. The following rules cause the most trouble:
| Block | Treated as |
|---|---|
| ` ``` ` with no language | Rust, tested |
| ` ```rust ` | Rust, tested |
| ` ```text `, ` ```toml `, ` ```bash ` | Not Rust, not tested |
| Indented by four spaces | Rust, tested |
| ` ```ignore ` | Rust, listed as ignored, not compiled |
The indented case catches many people. An indented block inside a doc comment is Markdown code, and rustdoc compiles it as Rust. If you indent a shell snippet or sample output, you will get a confusing compile error. Use a fenced block with text or console for anything that is not Rust.
Merged doc tests in edition 2024
Compiling hundreds of tiny crates is slow. Crates on edition 2024 (with a recent toolchain) let rustdoc merge compatible examples into one compilation and one executable. Each example still runs as its own test. Merging is meant to be invisible, and it speeds up large suites.
A few examples cannot be merged safely, for instance those with crate-level attributes or ones that rely on process-wide state. rustdoc compiles those on their own. If an example needs a process to itself, you can request that with the standalone_crate attribute on its code block. Check the rustdoc book for the exact rules of your toolchain, since this area has changed recently.
Common failure causes
cannot find ... in this scope. The example forgot ause. Remember that nothing from your crate is imported automatically.the ? operator can only be used in a function that returns Result. The generatedmainreturns(). End the example withOk::<(), YourError>(()), as covered in the previous chapter's treatment of hidden lines and errors.- A private item error. The example touches something that is not
pub. Test it through the public API, or move that check into a unit test. - A test that passes alone but fails when filtered. Examples must not depend on each other. Each one runs in a separate program with no shared state.
- A snippet that fails because it is not Rust. Check for an indented block or a missing
texttag.
Exercise
An example in the doc comment of a private function fn internal() calls mycrate::internal(). Does the doc test run, and does it pass?
Show answer
rustdoc does collect and run doc tests on private items, so the test runs. It fails to compile, because each doc test is a separate crate that links to the library and can see only public items. internal is private, so the compiler reports a privacy error. Rewrite the example to use a public function that calls internal, or replace the example with a unit test inside the crate.
Exercise
You write a block indented by four spaces in a doc comment to show shell output. cargo test --doc now fails with a syntax error in that block. Why, and how do you fix it?
Show answer
rustdoc treats indented code blocks as Rust and tries to compile them as a doc test. The shell output is not valid Rust, so compilation fails. Replace the indented block with a fenced block that has a non-Rust language tag, such as text or console, so rustdoc does not test it.