Search code examples
rustrust-cargodoctestreadme

How can I tell cargo to run code test in documentation in my README.md?


I'm looking for a way to move some docs from lib.rs to README.rs so they show up on my crate on cargo. I moved the docs to README.rs, and added this to the top of lib.rs

#[doc(include="../README.md")]

But it generates an error that says

use doc = include_str! instead: #[doc = include_str!("../README.md")] warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! note: for more information, see issue #82730 https://github.com/rust-lang/rust/issues/82730

When I however migrate to use #[doc = include_str!("../README.md")] instead of #[doc(include="../README.md")], I get a warning,

warning: unknown doc attribute include_str

And then

warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! note: for more information, see issue #82730 https://github.com/rust-lang/rust/issues/82730

What is the proper syntax to get my README.md tested with cargo test?


Solution

  • The right syntax is,

    #[doc = include_str!("../README.md")]
    

    On the latest Rust, this will not generate a warning, of note though is that this doesn't show up separately in cargo test.

    If you have a failed test for example in your ../README.md you'll see it reported as,

    test src/lib.rs - sequence (line 22) ... FAILED
    

    That seems far from ideal, as the name of the file is lost and the line numbers are no longer relevant.