34 / 35

Beyond the Basics· 13 min read· Lesson 34 of 35

Testing Your App

Part 2 · Laravel Rust. Learn plain Rust #[test] first, then Laravel Rust's #[laravel::test]: send fake requests, check validation and the database, and fake queues and mail.

A test is a small program that checks your code does what you think it does. Imagine the café owner tasting every new drink recipe before it goes on the menu. If something is off, they find out in the kitchen, not from an unhappy customer.

In this lesson you will start with a quick refresher on plain Rust #[test], then see how Laravel Rust’s #[laravel::test] lets you run a whole fake request through your app and check the result, without starting a server.

Note

This lesson follows the official Testing guide (opens in new tab) and the queue, mail and workflow testing sections of their guides. Laravel Rust is in beta, so check the docs for changes.

Refresher: a plain Rust test

You met plain Rust tests in Your first test, which covers #[cfg(test)], #[test], assert_eq! and cargo test. Here is a short reminder, with one new idea: reading a failure. Rust has testing built in. Mark a function with #[test], and cargo test runs it. Tests usually live in a tests module at the bottom of the file, marked #[cfg(test)] so it is only compiled during testing.

src/lib.rs
pub fn order_total_cents(price_cents: u32, quantity: u32) -> u32 {
price_cents * quantity
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn total_is_price_times_quantity() {
assert_eq!(order_total_cents(450, 2), 900);
}
}
  1. order_total_cents is the code under test. Money is stored as integer cents (u32), as in the Rust lessons.
  2. use super::*; brings the parent module’s items into the test module.
  3. assert_eq!(left, right) panics if the two values differ. A panic means a failed test.

Run it:

Terminal window
cargo test
Output
running 1 test
test tests::total_is_price_times_quantity ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

If the function were wrong, you would see something like this:

Output
---- tests::total_is_price_times_quantity stdout ----
thread 'tests::total_is_price_times_quantity' panicked at src/lib.rs:11:9:
assertion `left == right` failed
left: 904
right: 900

Read it from the top: which test failed, where, and the two values it compared. Besides assert_eq!, you also have assert! and assert_ne!.

Laravel tests: #[laravel::test]

Laravel puts integration tests in the tests/ directory. A test with no parameters is just a lightweight unit test. A test that takes an Application parameter gets its own fresh copy of your app:

tests/menu.rs
use laravel::testing::prelude::*;
#[laravel::test]
async fn the_menu_page_loads(app: Application) {
app.get("/menu").await.assert_ok();
}

Step by step:

  1. laravel::testing::prelude::* imports the test helpers.
  2. app: Application asks for an isolated application. Per the guide, each test also gets an isolated clock, cache and services, so tests running at the same time never interfere.
  3. app.get("/menu").await sends a GET request through your full middleware, routing and handler stack. No network port is used.
  4. .assert_ok() checks for a 200 status.

Every assertion returns the response, so you can chain checks:

app.get("/menu").await.assert_ok().assert_see("Latte");

Run everything with cargo test, or just some tests with cargo test menu.

The form we are testing

The next three tests target one handler: POST /orders, which we finish in the capstone. It builds on the order form from Typed Validation and Forms and expects a signed-in customer. Its input struct looks like this:

src/http/handlers/orders.rs
#[laravel::input(fills = Order)]
#[validate(authenticated)]
pub struct StoreOrder {
#[validate(required, max_length(100))]
pub customer_name: String,
#[validate(max_length(500))]
pub note: Option<String>,
#[fill(skip)]
#[validate(required, exists(MenuItem::id))]
pub menu_item_id: i64,
#[fill(skip)]
#[validate(required, min_value(1), max_value(20))]
pub quantity: i64,
}

Because of #[validate(authenticated)], a guest is sent to the login page. That is a rule we can test, and it also means every other test must act as a logged-in user.

Sending forms and checking validation

Use .form(...) to submit fields as a browser would. When validation fails, Laravel redirects back with errors, and the test client has assertions for that. To act as a signed-in customer, create a user with create! and add .acting_as(&user) to the request:

tests/orders.rs
use app::models::{MenuItem, User};
use laravel::model::create;
use laravel::testing::prelude::*;
#[laravel::test]
async fn guests_must_sign_in_to_order(app: Application) {
app.post("/orders")
.form([("customer_name", "Mina"), ("menu_item_id", "1"), ("quantity", "1")])
.await
.assert_redirect_to("/login");
}
#[laravel::test]
async fn quantity_must_be_at_least_one(app: Application) -> laravel::Result<()> {
let user = create!(User {
name: "Mina",
email: "mina@example.com",
password: "password",
})
.await?;
let latte = create!(MenuItem { name: "Latte", price_cents: 450 }).await?;
let latte_id = latte.id.to_string();
app.post("/orders")
.acting_as(&user)
.from("/menu")
.form([
("customer_name", "Mina"),
("menu_item_id", latte_id.as_str()),
("quantity", "0"),
])
.await
.assert_invalid(&["quantity"])
.assert_valid(&["customer_name", "menu_item_id"]);
Ok(())
}
  1. The first test posts as a guest and expects the redirect to /login. A guest could never reach the handler, so no order is made.
  2. The second test creates a customer and a menu item, then posts quantity = 0.
  3. .from("/menu") sets the Referer header, so the redirect-back that follows a failed validation has somewhere to go.
  4. assert_invalid lists the fields that must have errors, and assert_valid lists the ones that must not. Checking the field names means the test fails if validation fails for a different reason.

For JSON APIs, use .json(json!({ ... })) instead of .form(...).

Testing the database

Tests that save orders need a real database. With refresh_database() (already in new apps’ src/testing.rs), each test gets its own database copy, and its changes are rolled back when it ends. Create the rows you need with create!, and verify what your app wrote with the database assertions:

tests/orders.rs
#[laravel::test]
async fn a_valid_order_is_saved(app: Application) -> laravel::Result<()> {
let user = create!(User {
name: "Mina",
email: "mina@example.com",
password: "password",
})
.await?;
let latte = create!(MenuItem { name: "Latte", price_cents: 450 }).await?;
let latte_id = latte.id.to_string();
app.post("/orders")
.acting_as(&user)
.form([
("customer_name", "Mina"),
("menu_item_id", latte_id.as_str()),
("quantity", "2"),
])
.await
.assert_redirect_to("/menu");
app.assert_database_count("orders", 1).await;
app.assert_database_count("order_items", 1).await;
Ok(())
}

The test returns laravel::Result<()> so you can use ?. In an integration test, your own code is reached through the application’s crate name, which the guide writes as app (as in use app::services::Stripe;). The last two lines would fail if the redirect happened for the wrong reason, such as a validation failure, because no rows would exist. Other helpers include assert_database_has, assert_database_missing and assert_database_empty.

Warning

Auto-increment IDs keep counting between tests because a rollback does not reset them. Assert on the IDs your app returns, not hard-coded numbers like 1. (The guest test above uses "1" only because the guest never reaches the database.)

Fakes: checking without really doing

You do not want tests to send real email or push real jobs. A fake intercepts the call and records it so you can assert on it. The guide says each fake() returns a handle that must be kept in a variable, because the fake stays active only while the handle lives.

tests/receipts.rs
use app::jobs::SendReceipt;
use app::models::{MenuItem, User};
use laravel::http::client;
use laravel::model::create;
use laravel::queue;
use laravel::testing::prelude::*;
#[laravel::test]
async fn placing_an_order_queues_a_receipt(app: Application) -> laravel::Result<()> {
let user = create!(User {
name: "Mina",
email: "mina@example.com",
password: "password",
})
.await?;
let latte = create!(MenuItem { name: "Latte", price_cents: 450 }).await?;
let latte_id = latte.id.to_string();
let queue = queue::fake();
let _http = client::fake();
app.post("/orders")
.acting_as(&user)
.form([
("customer_name", "Mina"),
("menu_item_id", latte_id.as_str()),
("quantity", "2"),
])
.await
.assert_redirect_to("/menu");
queue.assert_pushed::<SendReceipt>();
Ok(())
}

queue::fake() stops jobs from running and records them. assert_pushed::<SendReceipt>() checks one was queued. client::fake() blocks real outgoing web requests (the capstone’s kitchen ping), and the leading underscore in _http keeps the handle alive without an “unused variable” warning.

Mail has a fake too. If you leave the queue unfaked, the sync queue runs SendReceipt right away, so the email counts as sent:

use laravel::mail;
let mail = mail::fake();
// ... post the same order as above ...
mail.assert_sent_where::<OrderReceipt>(|sent| sent.has_to("mina@example.com"));

There are fakes for events, broadcasting, file storage, notifications and more. You can also test a job’s handle directly with app.job(SendReceipt { order_id }), then chain .assert_succeeded().

Tip

In tests, Laravel sends jobs to the sync queue by default, so they run immediately, unless you fake the queue. Faking is how you check “was it queued?” separately from “does the job work?”.

Acting as a user and travelling in time

You already used .acting_as(&user) above to pretend a customer is logged in. To test things that depend on time, move your app’s clock instead of waiting:

app.travel(25.hours());

This is how workflow tests work too. Here is the shape of a test for the loyalty workflow, based on the guide’s onboarding example:

let run = app.workflow(WelcomeCustomer { customer_id: customer.id }).await;
run.assert_sleeping();
app.travel(3.days());
run.advance().await;
run.assert_completed();

app.workflow(..) starts the run, travel moves the clock forward, and advance() wakes the run. In tests, workflows use an in-memory store, so no extra tables are needed.

Try it yourself

  1. Write a plain Rust test for a function fn cents_to_dollars_text(cents: u32) -> String that turns 450 into "4.50". Include the function.
  2. Write a #[laravel::test] that checks GET /menu returns a successful response.
Show solution
pub fn cents_to_dollars_text(cents: u32) -> String {
format!("{}.{:02}", cents / 100, cents % 100)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_cents() {
assert_eq!(cents_to_dollars_text(450), "4.50");
assert_eq!(cents_to_dollars_text(5), "0.05");
}
}
use laravel::testing::prelude::*;
#[laravel::test]
async fn the_menu_loads(app: Application) {
app.get("/menu").await.assert_ok();
}

Recap

  • #[test] plus assert_eq! and cargo test is how plain Rust testing works.
  • #[laravel::test] with an Application parameter boots an isolated app. app.get(..) and app.post(..) send requests without a server.
  • Chain assertions such as assert_ok, assert_redirect, assert_invalid and assert_database_count.
  • Fakes such as queue::fake() and mail::fake() record what happened without really doing it.
  • app.travel(..) moves the clock, which is how you test waiting.

What’s next

You now have every tool for the finale. Build the whole café site in the Capstone: Rusty Bean Café Orders App.

0 of 35 lessons complete

Search lessons

Type to search all lessons.