How run doctest and tests?

Hello.
I have custom file with tests - tests.rs and tests in comments :

/// Checks whether the number is in a range
/// 
/// # Examples
///
/// ` ``
/// let result = check_conclude((0, 10), 2);
/// assert_eq!(result, true);
///
/// let result = check_conclude((0, 10), 11);
/// assert_eq!(result, false);
/// ``` 

i my main.rs file :

#[cfg(test)]
#[path = "./tests.rs"]
mod tests; 

Only tests from the tests.rs file are run.
How to make them all start?

Doctests are only run for library crates. You can add a lib.rs to your project, put modules/functions that contain doctests in the library, and then import them from your library into your binary with use my_project_name::foo::bar; to access them from main.rs and its submodules.

1 Like

You may be referring to something like:

/// ```rust
/// assert_ne!(2, 2);
/// ```
#[cfg(test)]
mod tests
{
    // and also:

    /// ```rust
    /// assert_ne!(2, 2);
    /// ```
    fn foo ...

    // ...
}

not working.

This is because cargo test --doc / rustdoc --test will only analyze the docstrings of the library built without #[cfg(test)], menaing that the whole tests module and its contents are non-existent at that time. It may be surprising, but it makes sense to consider that testing code not be part of the documentation of your crate.


If you still want to do it, you can hack your way around it by doing:

RUSTDOCFLAGS="--cfg test" cargo test

or by having

[build]
rustdocflags = ["--cfg", "test"]

in your .cargo/config file.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.