Crate include_doc

source ·
Expand description

Include Rust source files as doctests.

Examples

Using file!

file! lets you include an example source file as a doctest. It does 2 things:

  • fn main() will be stripped from the file.
  • All top level use statements will be hidden in the doctest.

The files for this example can be found under /example/ in this repository.

We use file! to provide an example for my_function in src/doc_with_example.rs. The example is in examples/my_example.rs:

use include_doc_example::doc_with_example::my_function;

fn main() {
    my_function();
}

In src/doc_with_example.rs, we add a doc comment to my_function where we include the example using file!:

/// # Examples
///
/// An example from `examples/my_example.rs`:
///
/// ```
#[doc = include_doc::file!("examples/my_example.rs")]
/// ```
pub fn my_function() {}

Using function_body!

function_body! is similar to file!, but allows you to specify which function body you want to use as the doctest. This is useful if you want to reduce boilerplate for imports or supporting code, as you can put many examples in one file. You can also specify which parts of the supporting code to include.

Usage is:

include_doc::function_body!(
    filename,
    function_name,
    [fn_dependency, StructDependency, ...]
);

In src/doc_with_tests.rs, we add a doc comment to my_function where we include the example using function_body!:

/// # Examples
///
/// Examples from `tests/doc.rs`:
///
/// ## First Example
///
/// ```
#[doc = include_doc::function_body!("tests/doc.rs", my_first_example, [MyFirstStruct, setup_first_example])]
/// ```
/// 
/// ## Second Example
/// ```
#[doc = include_doc::function_body!("tests/doc.rs", my_second_example, [MySecondStruct, setup_second_example])]
/// ```
pub fn my_function() {}

Macros

Include a Rust file as a doctest.
Include the function body from a Rust file as a doctest.