Part of the series about the Rocket web framework.
In the previous article where we saw how to write Hello World in Web Rocket we also included some test.
It was more straight forward to include the tests in the main.rs
, but in reality I think it is better to have them in separate files.
So in this article we see and example how to do it.
Dependencies
examples/rocket/hello-world-external-test-file/Cargo.toml
[package]
name = "hello-world-external-test-file"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = "0.5.0"
These are the same as in the previous version.
The tests
#[cfg(test)]
mod test {
...
}
The tests from inside the mod test
were moved to a separate file called src/tests.rs
.
examples/rocket/hello-world-external-test-file/src/tests.rs
use rocket::http::Status;
use rocket::local::blocking::Client;
#[test]
fn hello_world() {
let client = Client::tracked(super::rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string(), Some("Hello, world!".into()));
}
The code
The curly braces were also removed so this is the code:
examples/rocket/hello-world-external-test-file/src/main.rs
#[macro_use]
extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
#[cfg(test)]
mod tests;