Search code examples
unit-testingrustrust-cargo

undeclared crate or module inside `if cfg!(test)` even if defined in dev-dependencies


Here is the error:

let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
          ^^^^^^^ use of undeclared crate or module `tempdir`

My cargo.toml looks like this:

#...
[dev-dependencies]
tempdir = "0.3.7

And in the code:

let path = if cfg!(test) {
            let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
            tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
        } else {
            path
        };

I do not understand why it fails, when i run cargo test. :(


Solution

  • The cfg! macro evaluates to a constant true or false depending on the contents, so on non-test builds it evaluates to

    let path = if false {
        let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
        tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
    } else {
        path
    };
    

    which still has the dependency in it, and will type check everything and so it sees the missing crate. Instead you have to remove the whole first block from compilation:

    #[cfg(test)]
    let path = {
        let tmp = tempdir::TempDir::new("cargo_test").expect("failed to create tempdir");
        tmp.path().to_str().map(|x| x.to_string()).unwrap_or(path)
    };