Testing

Every application should be well tested and understandable. Rocket provides the tools to perform unit and integration tests. It also provides a means to inspect code generated by Rocket.

Local Dispatching

Rocket applications are tested by dispatching requests to a local instance of Rocket. The local module contains all of the structures necessary to do so. In particular, it contains a Client structure that is used to create LocalRequest structures that can be dispatched against a given Rocket instance. Usage is straightforward:

  1. Construct a Rocket instance that represents the application.

    1. let rocket = rocket::ignite();
  2. Construct a Client using the Rocket instance.

    1. let client = Client::new(rocket).expect("valid rocket instance");
  3. Construct requests using the Client instance.

    1. let req = client.get("/");
  4. Dispatch the request to retrieve the response.

    1. let response = req.dispatch();

Validating Responses

A dispatch of a LocalRequest returns a LocalResponse which can be used transparently as a Response value. During testing, the response is usually validated against expected properties. These includes things like the response HTTP status, the inclusion of headers, and expected body data.

The Response type provides methods to ease this sort of validation. We list a few below:

  • status: returns the HTTP status in the response.
  • content_type: returns the Content-Type header in the response.
  • headers: returns a map of all of the headers in the response.
  • body_string: returns the body data as a String.
  • body_bytes: returns the body data as a Vec<u8>.

These methods are typically used in combination with the assert_eq! or assert! macros as follows:

  1. let rocket = rocket::ignite();
  2. let client = Client::new(rocket).expect("valid rocket instance");
  3. let mut response = client.get("/").dispatch();
  4. assert_eq!(response.status(), Status::Ok);
  5. assert_eq!(response.content_type(), Some(ContentType::Plain));
  6. assert!(response.headers().get_one("X-Special").is_some());
  7. assert_eq!(response.body_string(), Some("Expected Body.".into()));

Testing “Hello, world!”

To solidify an intuition for how Rocket applications are tested, we walk through how to test the “Hello, world!” application below:

  1. #[get("/")]
  2. fn hello() -> &'static str {
  3. "Hello, world!"
  4. }
  5. fn rocket() -> Rocket {
  6. rocket::ignite().mount("/", routes![hello])
  7. }
  8. fn main() {
  9. rocket().launch();
  10. }

Notice that we’ve separated the creation of the Rocket instance from the launch of the instance. As you’ll soon see, this makes testing our application easier, less verbose, and less error-prone.

Setting Up

First, we’ll create a test module with the proper imports:

  1. #[cfg(test)]
  2. mod test {
  3. use super::rocket;
  4. use rocket::local::Client;
  5. use rocket::http::Status;
  6. #[test]
  7. fn hello_world() {
  8. ...
  9. }
  10. }

You can also move the body of the test module into its own file, say tests.rs, and then import the module into the main file using:

  1. #[cfg(test)] mod tests;

Testing

To test our “Hello, world!” application, we first create a Client for our Rocket instance. It’s okay to use methods like expect and unwrap during testing: we want our tests to panic when something goes wrong.

  1. let client = Client::new(rocket()).expect("valid rocket instance");

Then, we create a new GET / request and dispatch it, getting back our application’s response:

  1. let mut response = client.get("/").dispatch();

Finally, we ensure that the response contains the information we expect it to. Here, we want to ensure two things:

  1. The status is 200 OK.
  2. The body is the string “Hello, world!”.

We do this by checking the Response object directly:

  1. assert_eq!(response.status(), Status::Ok);
  2. assert_eq!(response.body_string(), Some("Hello, world!".into()));

That’s it! Altogether, this looks like:

  1. #[cfg(test)]
  2. mod test {
  3. use super::rocket;
  4. use rocket::local::Client;
  5. use rocket::http::Status;
  6. #[test]
  7. fn hello_world() {
  8. let client = Client::new(rocket()).expect("valid rocket instance");
  9. let mut response = client.get("/").dispatch();
  10. assert_eq!(response.status(), Status::Ok);
  11. assert_eq!(response.body_string(), Some("Hello, world!".into()));
  12. }
  13. }

The tests can be run with cargo test. You can find the full source code to this example on GitHub.

Codegen Debug

It can be useful to inspect the code that Rocket’s code generation is emitting, especially when you get a strange type error. To have Rocket log the code that it is emitting to the console, set the ROCKET_CODEGEN_DEBUG environment variable when compiling:

  1. ROCKET_CODEGEN_DEBUG=1 cargo build

During compilation, you should see output like:

  1. Emitting item:
  2. fn rocket_route_fn_hello<'_b>(
  3. __req: &'_b ::rocket::Request,
  4. __data: ::rocket::Data
  5. ) -> ::rocket::handler::Outcome<'_b> {
  6. let responder = hello();
  7. ::rocket::handler::Outcome::from(__req, responder)
  8. }

This corresponds to the facade request handler Rocket has generated for the hello route.