diff --git a/examples/optional_redirect/Cargo.toml b/examples/optional_redirect/Cargo.toml index e7e29b0b..55b32c96 100644 --- a/examples/optional_redirect/Cargo.toml +++ b/examples/optional_redirect/Cargo.toml @@ -7,3 +7,6 @@ workspace = "../../" [dependencies] rocket = { path = "../../lib" } rocket_codegen = { path = "../../codegen" } + +[dev-dependencies] +rocket = { path = "../../lib", features = ["testing"] } diff --git a/examples/optional_redirect/src/main.rs b/examples/optional_redirect/src/main.rs index 72f62dda..95ee9911 100644 --- a/examples/optional_redirect/src/main.rs +++ b/examples/optional_redirect/src/main.rs @@ -2,6 +2,9 @@ #![plugin(rocket_codegen)] extern crate rocket; +#[cfg(test)] +mod tests; + use rocket::response::Redirect; #[get("/")] @@ -13,7 +16,7 @@ fn root() -> Redirect { fn user(name: &str) -> Result<&'static str, Redirect> { match name { "Sergio" => Ok("Hello, Sergio!"), - _ => Err(Redirect::to("/users/login")) + _ => Err(Redirect::to("/users/login")), } } diff --git a/examples/optional_redirect/src/tests.rs b/examples/optional_redirect/src/tests.rs new file mode 100644 index 00000000..d7e50c07 --- /dev/null +++ b/examples/optional_redirect/src/tests.rs @@ -0,0 +1,38 @@ +use super::rocket; +use rocket::testing::MockRequest; +use rocket::http::{Method, Status}; + +fn test_200(uri: &str, expected_body: &str) { + let rocket = rocket::ignite() + .mount("/", routes![super::root, super::user, super::login]); + let mut request = MockRequest::new(Method::Get, uri); + let mut response = request.dispatch_with(&rocket); + + assert_eq!(response.status(), Status::Ok); + assert_eq!(response.body().and_then(|b| b.into_string()), + Some(expected_body.to_string())); +} + +fn test_303(uri: &str, expected_location: &str) { + let rocket = rocket::ignite() + .mount("/", routes![super::root, super::user, super::login]); + let mut request = MockRequest::new(Method::Get, uri); + let response = request.dispatch_with(&rocket); + let location_headers: Vec<_> = response.header_values("Location").collect(); + + assert_eq!(response.status(), Status::SeeOther); + assert_eq!(location_headers, vec![expected_location]); +} + +#[test] +fn test() { + test_200("/users/Sergio", "Hello, Sergio!"); + test_200("/users/login", + "Hi! That user doesn't exist. Maybe you need to log in?"); +} + +#[test] +fn test_redirects() { + test_303("/", "/users/login"); + test_303("/users/unknown", "/users/login"); +}