Search code examples
rustrustdoc

How to use a module with the `test` attribute within doc tests?


I have a module which I would like to use within a code block in my documentation.

This module is only used for tests, so it has the #![cfg(test)] attribute which it should keep.

However, as a result, this file does not seem to be included when running tests on the documentation.

Take a look at the MVCE:

lib.rs

//! ```
//! use example::mock::Number;
//! ```
pub mod mock;

pub fn main() {}

mock.rs

#![cfg(test)]

pub type Number = i32;

This fails with:

---- src/lib.rs -  (line 1) stdout ----
error[E0432]: unresolved import `example::mock`
 --> src/lib.rs:2:14
  |
4 | use example::mock::Number;
  |              ^^^^ could not find `mock` in `example`

Is there a way to make my documentation test code use these files which are configured for tests?


Solution

  • This is a known limitation of doctest (Issue #45599). Sadly there is no real progress since the start of the issue (late 2017).

    As a workaround, it is suggested that you add a feature to your Cargo.toml

    [features]
    test = []
    

    Instead of checking for #[cfg(test)] you can then do #[cfg(feature = "test")].