56

I'm writing a Rust library and I want to provide examples in my documentation that

  1. compile as part of running cargo test
  2. do not run.

Is this possible?

I'm writing a database client library, and the examples make use of a hypothetical, non-existing database server. As such, the examples always fail when run, but it's important that the examples be valid syntactically. Hence my requirements above.

If there's no way to do what I want, then how does one opt out of having cargo test run a specific doc test? I.e., have cargo run compile-and-run some doc tests but completely ignore some others?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Craig M. Brandenburg
  • 3,354
  • 5
  • 25
  • 37

2 Answers2

64

This is documented in The rustdoc book, specifically the chapter about attributes.

Your opening codeblock delimiter should look like:

/// ```no_run

From the book:

/// ```no_run
/// loop {
///     println!("Hello, world");
/// }
/// ```

The no_run attribute will compile your code, but not run it. This is important for examples such as "Here's how to retrieve a web page," which you would want to ensure compiles, but might be run in a test environment that has no network access.

To omit build completely use ignore instead of no_run.

fbucek
  • 1,647
  • 13
  • 22
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
  • 5
    I think in later versions of Rust `no_run` no longer works, but the book doesn't seem to be clear about what replaced it. – snim2 Jun 08 '18 at 13:17
  • 2
    Coming from 2022, and `no_run` worked just fine for me on the latest stable rust + cargo as of this comment posting date (I got the `passed` message for the test when running them) – Kobato Jul 01 '22 at 13:23
43

Put this in Cargo.toml:

[lib]
doctest = false

Found it here: https://doc.rust-lang.org/cargo/commands/cargo-test.html

Ray Hulha
  • 10,701
  • 5
  • 53
  • 53