Course › Week 6 · Laravel Rust › Day 7 · lesson 42 of 42 · 20 min reading + 1–2 h practice
Tests and the Week 6 checkpoint
#[laravel::test] with HTTP and queue fakes, and when to pick axum, Laravel Rust or PHP Laravel.
On this page
The tests of the Week 5 checkpoint built the router by hand, sent requests with oneshot and read the bodies with http-body-util. A Laravel developer would recognise none of it. The tests here read like a feature test in tests/Feature, because Laravel Rust ships the same helpers: $this->postJson(), Http::fake(), Queue::fake(), assertDatabaseHas.
1. The test settings
src/testing.rs is where the tests’ application is built: the skeleton’s .env overrides, and refresh_database(), which gives each test a database of its own, migrated from scratch. The QUEUE_CONNECTION=sync override means a dispatched job runs at once, inside the test.
The two required variables get test values here, so the tests run with no .env at all, as in CI. analysis.test is a domain that never resolves: a request the tests forgot to fake fails instead of reaching a real API.
19 unchanged lines
use laravel::Application;use laravel::foundation::ApplicationBuilder; /// Create a fresh application for tests, reading `.env.testing` or `.env` with the overrides below.pub fn create() -> Application { configure().create()} pub fn configure() -> ApplicationBuilder { crate::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_envs([ ("APP_ENV", "testing"), ("APP_DEBUG", "true"), ("BCRYPT_ROUNDS", "4"), ("BROADCAST_CONNECTION", "discard"), ("CACHE_STORE", "memory"), ("FEATURE_STORE", "memory"), ("INERTIA_SSR", "false"), ("MAIL_MAILER", "log"), ("OTEL_SDK_DISABLED", "true"), ("QUEUE_CONNECTION", "sync"), ("SERVICE_API_KEY", "test-key-0123456789"), ("ANALYSIS_URL", "http://analysis.test/api/analyse"), ("SEARCH_ENGINE", "database"), ("SESSION_DRIVER", "memory"), ("SMS_SENDER", "log"), ("WORKFLOW_STORE", "memory"), ]) .refresh_database()}
2. The tests
#[laravel::test] with an app: Application argument gets a fresh application. app.post(uri).header(…).json(…).await sends a request through every middleware and handler without a server, and returns a response with assertions: assert_accepted, assert_status(409), assert_json for a partial match, assert_json_path for one value.
queue::fake() records dispatched jobs instead of running them, and client::fake().with(pattern, response) answers outgoing HTTP calls, client::failed_connection() included. Both stay active until their handle is dropped, which is why the handles are kept in variables, _queue and _http when nothing asserts on them.
app.job(AnalyseBatch { … }) runs one attempt of a job, with no worker and no retries, and assert_succeeded or assert_failed checks the outcome. app.assert_database_has(table, columns) reads the table, as assertDatabaseHas does.
//! The batch API from the outside: each test gets a fresh application and a fresh database, and
//! the analysis API is faked, so no test touches the network.
use app::jobs::AnalyseBatch;
use app::models::{AnalysisBatch, Answer, Evaluation};
use laravel::http::client;
use laravel::model::create;
use laravel::queue;
use laravel::testing::prelude::*;
const KEY: &str = "test-key-0123456789";
/// One evaluation with a comment, the smallest batch that has something to analyse.
async fn an_evaluation() -> laravel::Result<Evaluation> {
let evaluation = create!(Evaluation {
school: "Alexandria STEM"
})
.await?;
create!(Answer {
evaluation: &evaluation,
question: "Q1",
score: 5_i16,
comment: "Clear explanations"
})
.await?;
Ok(evaluation)
}
#[laravel::test]
async fn batches_need_the_key(app: Application) {
app.post("/api/batches")
.json(json!({ "reference": "a", "evaluation_ids": [1] }))
.await
.assert_status(401);
app.get("/api/status").await.assert_ok();
}
#[laravel::test]
async fn a_new_batch_is_queued_once(app: Application) {
let queue = queue::fake();
let batch = json!({ "reference": "dashboard-1", "evaluation_ids": [2, 1, 1] });
app.post("/api/batches")
.header("x-api-key", KEY)
.json(batch.clone())
.await
.assert_accepted();
app.post("/api/batches")
.header("x-api-key", KEY)
.json(batch)
.await
.assert_ok();
app.assert_database_count("analysis_batches", 1).await;
app.assert_database_has(
"analysis_batches",
json!({ "reference": "dashboard-1", "status": "queued" }),
)
.await;
// The retry pushed a second job for the still-queued batch: two jobs, one batch.
queue.assert_pushed_times::<AnalyseBatch>(2);
}
#[laravel::test]
async fn a_reference_cannot_be_reused_for_other_ids(app: Application) {
let _queue = queue::fake();
app.post("/api/batches")
.header("x-api-key", KEY)
.json(json!({ "reference": "r", "evaluation_ids": [1] }))
.await;
app.post("/api/batches")
.header("x-api-key", KEY)
.json(json!({ "reference": "r", "evaluation_ids": [2] }))
.await
.assert_status(409)
.assert_json(json!({ "message": "This reference was already used for other evaluations." }));
}
#[laravel::test]
async fn an_empty_batch_is_invalid(app: Application) {
app.post("/api/batches")
.header("x-api-key", KEY)
.json(json!({ "reference": "r", "evaluation_ids": [] }))
.await
.assert_unprocessable()
.assert_json_path("errors.evaluation_ids.0", "The evaluation ids field is required.");
}
#[laravel::test]
async fn the_job_saves_results_and_failures(app: Application) -> laravel::Result<()> {
let http = client::fake().with(
"analysis.test/*",
json!({ "evaluation_id": 1, "positive": 1, "negative": 0, "neutral": 0 }),
);
let evaluation = an_evaluation().await?;
let batch = create!(AnalysisBatch {
reference: "b",
evaluation_ids: laravel::db::Json(vec![evaluation.id, 99])
})
.await?;
app.job(AnalyseBatch { batch_id: batch.id }).await.assert_succeeded();
app.assert_database_has(
"analysis_batches",
json!({ "id": batch.id, "status": "done", "analysed": 1, "failed": 1 }),
)
.await;
app.assert_database_has(
"evaluations",
json!({ "id": evaluation.id, "status": "analysed", "positive": 1 }),
)
.await;
app.assert_database_has(
"analysis_batch_failures",
json!({ "evaluation_id": 99, "retryable": false }),
)
.await;
http.assert_sent_count(1);
Ok(())
}
#[laravel::test]
async fn an_unreachable_api_saves_nothing(app: Application) -> laravel::Result<()> {
let _http = client::fake().with("analysis.test/*", client::failed_connection());
let evaluation = an_evaluation().await?;
let batch = create!(AnalysisBatch {
reference: "c",
evaluation_ids: laravel::db::Json(vec![evaluation.id])
})
.await?;
app.job(AnalyseBatch { batch_id: batch.id }).await.assert_failed();
app.assert_database_empty("analysis_batch_failures").await;
app.assert_database_has("evaluations", json!({ "id": evaluation.id, "status": "pending" }))
.await;
Ok(())
}
#[laravel::test]
async fn running_the_job_twice_changes_nothing(app: Application) -> laravel::Result<()> {
let _http = client::fake().with(
"analysis.test/*",
json!({ "evaluation_id": 1, "positive": 1, "negative": 0, "neutral": 0 }),
);
let evaluation = an_evaluation().await?;
let batch = create!(AnalysisBatch {
reference: "d",
evaluation_ids: laravel::db::Json(vec![evaluation.id, 99])
})
.await?;
app.job(AnalyseBatch { batch_id: batch.id }).await.assert_succeeded();
app.job(AnalyseBatch { batch_id: batch.id }).await.assert_succeeded();
app.assert_database_count("analysis_batch_failures", 1).await;
Ok(())
}
running 1 test
test the_api_reports_laravels_version ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s
running 7 tests
test a_new_batch_is_queued_once ... ok
test an_empty_batch_is_invalid ... ok
test an_unreachable_api_saves_nothing ... ok
test batches_need_the_key ... ok
test running_the_job_twice_changes_nothing ... ok
test the_job_saves_results_and_failures ... ok
test a_reference_cannot_be_reused_for_other_ids ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.24s
running 1 test
test the_welcome_page_renders ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02sNine tests: the skeleton’s two (the version route and the welcome page) and the seven above, each against its own database, in a fraction of a second. Each one guards a promise of the build day: the key, the retry that returns the same batch, the 409, the Laravel-shaped 422, results and failures saved together, nothing saved when the API is down, and a second run that changes nothing.
3. Problem: a refactor drops one early return
A teammate shortens the job: the batch is set to running right away, so the check for a finished batch looks redundant, and the four lines go. Everything compiles, and the batch still ends done:
let mut batch = AnalysisBatch::find_or_fail(self.batch_id).await?;
update!(batch { status: BatchStatus::Running }).await?;
running 1 test
test the_api_reports_laravels_version ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.26s
running 7 tests
test a_new_batch_is_queued_once ... ok
test an_empty_batch_is_invalid ... ok
test an_unreachable_api_saves_nothing ... ok
test batches_need_the_key ... ok
test running_the_job_twice_changes_nothing ... FAILED
test the_job_saves_results_and_failures ... ok
test a_reference_cannot_be_reused_for_other_ids ... ok
failures:
---- running_the_job_twice_changes_nothing stdout ----
thread 'running_the_job_twice_changes_nothing' (5833) panicked at /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/laravel-rust-0.1.4/src/testing/database.rs:344:9:
expected the `analysis_batch_failures` table to have 1 row, but it has 2 rows
at tests/batches.rs:158:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
running_the_job_twice_changes_nothing
test result: FAILED. 6 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27sShow what went wrong
The second run of the job analysed the batch again and inserted its failure a second time: two rows for one failed evaluation. The batch can be run twice for ordinary reasons: the store handler pushes a second job when a retried request finds the batch still queued, and a worker that dies mid-job leaves the job for the next worker. The early return is what makes either harmless.
The test running_the_job_twice_changes_nothing exists for exactly this: a promise that is not obvious from the code, written down where a refactor cannot quietly break it. Put the four lines back.
4. Problem: a test without its fake
Someone copies a_new_batch_is_queued_once and leaves out queue::fake(), since the test does not assert on jobs any more:
running 1 test
test a_new_batch_is_queued_once ... FAILED
failures:
---- a_new_batch_is_queued_once stdout ----
thread 'a_new_batch_is_queued_once' (5981) panicked at /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/laravel-rust-0.1.4/src/testing/database.rs:344:9:
expected the `analysis_batches` table to have a row matching {"reference":"dashboard-1","status":"queued"}, but its only row is:
{"reference":"dashboard-1","status":"done"}
at tests/batches.rs:54:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
a_new_batch_is_queued_once
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.20sShow what went wrong
Without the fake, the test’s sync queue ran the job inside the POST request. Evaluations 1 and 2 do not exist in the test’s empty database, so the job saved two failures and marked the batch done before the response was even sent; the assertion expected queued and found done.
The failure message shows the row it found, which points straight at the cause. The fix is the fake. The lesson is general: in tests, a job dispatched without queue::fake() runs, with all its side effects, as Queue::fake() prevents in PHP. A test that does not fake the queue is a test of the job too, whether you meant it or not.
The Week 6 exit check
The week’s goal was to build a real service the Laravel Rust way and to know when to choose it. It is reached when each line holds on your machine:
| Check | How |
|---|---|
laravel new --rust, migrate, dev, route:list work, and you can find each folder’s PHP counterpart | The install lesson |
| Input is a struct with its rules; a route parameter’s type is its constraint | an_empty_batch_is_invalid, and /api/evaluations/abc answers 404 |
Models with typed columns; relationships loaded with with | The models lesson, and the with(AnalysisBatch::failures) of show |
| The application refuses to start without its required settings | laravel migrate with no SERVICE_API_KEY |
| A retried POST returns the same batch, even at the same moment | a_new_batch_is_queued_once, and the five parallel requests of the build day |
| Results all or nothing; the API down means a retry, not a half-saved batch | the_job_saves_results_and_failures, an_unreachable_api_saves_nothing |
| A job is safe to run twice | running_the_job_twice_changes_nothing |
cargo test, cargo clippy --all-targets and cargo fmt --check are clean | Before every push, or in CI |
| The PHP Laravel client of Week 5 talks to the new service unchanged | Its Http::fake tests from the Week 5 checkpoint, and one real call |
A Laravel feature test, and this one
| PHP Laravel | Laravel Rust |
|---|---|
use RefreshDatabase; | .refresh_database() in src/testing.rs: a new database per test, so tests run in parallel |
$this->withHeader(…)->postJson(…) | app.post(…).header(…).json(…).await |
->assertStatus(409)->assertJson([…]) | .assert_status(409).assert_json(json!({…})) |
Http::fake([…]), Queue::fake() | client::fake().with(…), queue::fake(), kept alive by their handle |
(new AnalyseBatch(1))->handle(…) | app.job(AnalyseBatch { batch_id }).await.assert_succeeded() |
$this->assertDatabaseHas(…) | app.assert_database_has(…).await |
Almost a translation, which is the point of the framework. One difference matters: RefreshDatabase rolls back a transaction per test, so code that commits its own transaction, like this job, is awkward to test with it; a database per test has no such limit.
PracticeThe testing guide, and two more tests
Read testing, and the “Testing” parts of queues and the HTTP client.
Exercise 1: one evaluation fails, one succeeds
Fake the analysis API with client::sequence(): one success, then client::failed_connection() for every later call (when_empty). With two evaluations, the batch must be done with one analysed and one failure with retryable: true.
Exercise 2: the failed hook
app.job runs one attempt and never calls failed. Write a test that calls the hook’s effect another way: create a running batch, run the job three times with attempt(n) against a failing API, and decide what the test can and cannot prove about the hook. Then read the queues guide on assert_failed.
Remember
#[laravel::test]withclient::fake,queue::fakeandapp.jobreads like a Laravel feature test; a test without its fake also tests what the fake would have stopped.
Next: what this week left out is in the crate’s own docs/ folder, matched to the version you installed: authentication, mail, the scheduler and durable workflows.