1

The structure of my code as below.

enter image description here

I ran 'cargo run' and it works. But when I ran 'cargo test', I got the errors as below. Could you please tell me why and how can I fix them?

error: cannot find attribute get in this scope

error: cannot find macro routes in this scope

src/main.rs

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

mod common;

fn main() {
    common::run();
}

src/common.rs

#[get("/hello")]
pub fn hello() -> &'static str {
    "hello"
}

pub fn run() {
    rocket::ignite().mount("/", routes![hello]).launch();
}

tests/development.rs

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[cfg(test)]
mod common;

#[test]
fn test_development_config() {
    common::run();
}

tests/common.rs

use rocket::http::Status;
use rocket::local::Client;

#[get("/check_config")]
fn check_config() -> &'static str {
    "hello"
}

pub fn run() {
    let rocket = rocket::ignite().mount("/", routes![check_config]);

    let client = Client::new(rocket).unwrap();
    let response = client.get("/hello").dispatch();
    assert_eq!(response.status(), Status::Ok);
}
Community
  • 1
  • 1
Brad C
  • 25
  • 3

1 Answers1

3

Each .rs file in the tests/ folder is separately compiled and executed as a test. So development.rs is compiled, "includes" common.rs and it works. But then common.rs is compiled individually and it fails because there is no #[macro_use] extern crate rocket; anywhere.

One solution would be to put your common.rs into tests/common/mod.rs. Files in sub-directories of tests are not automatically compiled as test.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305