12

These are the contents of my src/lib.rs file:

pub fn foo() {}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        foo();
    }
}

When I run cargo test, I get the following error:

error[E0425]: cannot find function `foo` in this scope
 --> src/lib.rs:7:9
  |
7 |         foo();
  |         ^^^ not found in this scope

How do I call foo from inside the test module?

1

1 Answer 1

19

You could use super:: to refer to the parent module:

fn it_works() {
    super::foo();
}

In Rust 2015, you can use :: to refer to the root module of the crate:

fn it_works() {
    ::foo();
}

In Rust 2018, you can use crate:: to refer to the root module of the crate:

fn it_works() {
    crate::foo();
}

Or, as foo may be used repeatedly, you could use it in the module:

mod tests {
    use foo;         // <-- import the `foo` from the root module
    // or
    use super::foo;  // <-- import the `foo` from the parent module

    fn it_works() {
        foo();
    }
}

For test modules, it's also common to import everything from the parent module:

mod tests {
    use super::*;  // <-- import everything from the parent module

    fn it_works() {
        foo();
    }
}
1
  • Thanks! I put use super::* since I'm not worried about namespace clouding in my own crate. Oct 14, 2016 at 1:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.