9
mod simulation;

use simulation::factory::FactoryType;

works fine in main.rs, but not in a doctest inside simulation/factory.rs:

impl product_type::ProductType for FactoryType {
    /// Lorem Ipsum
    ///
    /// # Examples
    ///
    /// ```
    /// use simulation::factory::FactoryType;
    ///
    /// ...
    /// ```
    fn human_id(&self) -> &String {
        ...
    }
}

cargo test gives me the error

---- simulation::factory::human_id_0 stdout ----
    <anon>:2:9: 2:19 error: unresolved import `simulation::factory::FactoryType`. Maybe a missing `extern crate simulation`?
<anon>:2     use simulation::factory::FactoryType;
                 ^~~~~~~~~~
error: aborting due to previous error
thread 'simulation::factory::human_id_0' panicked at 'Box<Any>', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libsyntax/diagnostic.rs:192

How can I get doctests to work?

wrongusername
  • 18,564
  • 40
  • 130
  • 214
  • 1
    If you're creating a binary (e.g. if one has `src/main.rs` instead of `src/lib.rs`) then you can't use the functions from it in a doctest: doc tests import the crate they're from as a library (if it is one). – huon Sep 09 '15 at 08:21
  • Please take the time to create an [MCVE](/help/mcve) when asking for help. As you've currently stated your question, we have to do a lot of guessing to know exactly what exists. – Shepmaster Sep 09 '15 at 13:59

2 Answers2

9

When you write a doc test, you have to act as the user of your code would. Given these files:

src/lib.rs

pub mod simulation {
    pub mod factory {
        pub struct FactoryType;

        impl FactoryType {
            /// ```
            /// use foo::simulation::factory::FactoryType;
            ///
            /// let f = FactoryType;
            /// assert_eq!(42, f.human_id())
            /// ```
            pub fn human_id(&self) -> u8 { 41 }
        }
    }
}

src/main.rs

extern crate foo;
use foo::simulation::factory::FactoryType;

fn main() {
    let f = FactoryType;
    println!("{}", f.human_id());
}

Everything works. Note that in main.rs, you have to say extern crate, then all your references need to include the crate name. The doctest is the same, except the extern crate is automatically included for you.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
3

As huon-dbaupp noted, bin crates cannot be imported from doc tests.

The solution is to define most of your code as a library crate and have one binary that is just a shell around that.

For example, racer employs this technique.

llogiq
  • 13,815
  • 8
  • 40
  • 72