Rust "doctest failed" - Failing Documentation Tests in CI
A code example inside a /// doc comment failed. Cargo compiles and runs doc examples as tests by default, so an out-of-date or non-compiling example breaks cargo test even when all unit tests pass.
What this error means
The Doc-tests <crate> section of cargo test reports a FAILED doctest with a compile error or panic from a doc-comment example. Unit and integration tests pass; only the documentation example is broken.
Doc-tests app
running 1 test
test src/lib.rs - add (line 3) ... FAILED
failures:
---- src/lib.rs - add (line 3) stdout ----
error[E0599]: no method named `to_owned_string` found for type `i32`
Couldn't compile the test.
test result: FAILED. 0 passed; 1 failed;
error: doctest failed, to rerun pass `--doc`Common causes
A doc example drifted out of date
The API changed but a /// example still calls the old method or signature. Cargo compiles the example, so it now fails to build.
Example expects different runtime behavior
The example runs and an assert_eq! (or implicit panic) inside it no longer holds, failing the doctest at runtime.
How to fix it
Update the example to the current API
Edit the doc-comment code so it compiles and its assertions hold against the real API.
/// ```
/// let s = app::add(2, 3);
/// assert_eq!(s, 5);
/// ```Annotate examples that shouldn’t run/compile
Use code-fence attributes for examples that are illustrative only.
/// ```no_run
/// // compiles but isn't executed
/// ```
/// ```ignore
/// // skipped entirely
/// ```
/// ```text
/// not Rust - shown as plain text
/// ```How to prevent it
- Keep
///examples in sync with API changes - they are real tests. - Run
cargo test --docin CI so doc examples are validated. - Use
no_run/ignore/textdeliberately for non-executable snippets.