Part 6: Actions and tests
An action: giving a book back
Not everything is a create, an update or a delete. Giving a book back is
an operation of its own, on one loan: POST /loans/{id}/give_back. In
DRF it is a method decorated with @action(detail=True, methods=["post"]). In rind it is a method in an #[actions] block:
#![allow(unused)] fn main() { // crates/lending/lending-api/src/loans/views.rs #[actions] impl LoanResource { /// Gives the book back: the loan is closed today. #[action(POST)] pub async fn give_back(ctx: &Ctx, mode: LoanMode, loan: Loan) -> Result<LoanOut, ApiError> { if loan.returned_on.is_some() { return Err(ApiError::BadRequest("This book was already given back.".into())); } let today = rind::db::chrono::Utc::now().date_naive(); ctx.db .execute( &Update::<Loan>::new() .set(Loan::returned_on(), Some(today)) .filter(Loan::id().eq(loan.id)), ) .await?; let loan = Loan { returned_on: Some(today), ..loan }; resource::serialize_one::<LoanResource>(ctx, mode, loan, &QueryParams::default()).await } } }
The action asks for what it needs by the types of its parameters:
ctx: &Ctx, the request's context;mode: LoanMode, the mode the rule gave;loan: Loan, the object of the URL. rind reads it inside the mode: when Alice asks for Bob's loan, the action does not even run, and the answer is a 404.
It can also take query parameters (#[query] name: T) and a JSON body
(#[body] body: T); see Actions.
Its answer is anything that serializes. Here we answer the loan as a
read would, with serialize_one, so that the mode hides the borrower as
usual.
The action is allowed by its name in the rules. give_back is in the
members' rule; the staff's rule lists no actions, so it allows all of
them.
curl -X POST -H "Authorization: Bearer $ALICE" localhost:8080/loans/1/give_back
{"book":1,"borrowed_on":"2026-11-27","id":1,"returned_on":"2026-11-27"}
curl -X POST -H "Authorization: Bearer $ALICE" localhost:8080/loans/1/give_back
{"detail":"This book was already given back."}
And a member cannot change a loan, since no rule gives them update or
partial_update:
curl -X PATCH -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"book": 2}' localhost:8080/loans/2
{"detail":"You do not have permission to perform this action."}
rind routes now shows the action:
lending
/loans GET POST
/loans/{id} GET PATCH PUT
/loans/{id}/give_back POST
Where should the work go? Our action is short, so its work is in the action itself. In a larger application, the work goes in a function of an
opscrate of the domain (lending-ops), which knows nothing of HTTP, and the action only calls it. The function can then be tested alone, and called from a command or a job. See Organising an application.
Testing
rind new wrote a first test, app/tests/schema.rs, which runs rind check inside cargo test. Let's add one that tells the story of this
tutorial over HTTP.
rind gives each test a PostgreSQL schema of its own, created and
migrated by rind::testing::fresh_schema. The tests can run in
parallel, and each starts from empty tables.
To send requests, we build the application's router and call it
directly, without a network, with tower's oneshot. Add the test
dependencies to app/Cargo.toml:
[dev-dependencies]
axum = "0.8"
http-body-util = "0.1"
serde_json.workspace = true
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tower = { version = "0.5", features = ["util"] }
And the test:
#![allow(unused)] fn main() { // app/tests/api.rs use axum::body::Body; use axum::http::Request; use http_body_util::BodyExt; use rind::prelude::*; use serde_json::{Value, json}; use tower::ServiceExt; /// Sends one request to the application, and reads its JSON answer. async fn call(db: &Db, method: &str, uri: &str, token: Option<&str>, body: Value) -> (u16, Value) { let app = app::app(); let mut request = Request::builder() .method(method) .uri(uri) .header("Content-Type", "application/json"); if let Some(token) = token { request = request.header("Authorization", format!("Bearer {token}")); } let response = app .router(app.state(db.clone())) .oneshot(request.body(Body::from(body.to_string())).unwrap()) .await .unwrap(); let status = response.status().as_u16(); let bytes = response.into_body().collect().await.unwrap().to_bytes(); (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) } #[tokio::test] async fn a_member_borrows_a_book_and_gives_it_back() { let Some(db) = rind::testing::fresh_schema(&app::app(), "test_loans").await else { return; }; // An author, a book and a member, written straight into the database. db.batch_execute( "INSERT INTO catalog_author (id, name) VALUES (1, 'Frank Herbert'); INSERT INTO catalog_book (id, title, year, author_id) VALUES (1, 'Dune', 1965, 1); INSERT INTO auth_user (id, username) VALUES (1, 'alice');", ) .await .unwrap(); rind_auth::passwords::<rind_auth::models::User>(&app::app()) .unwrap() .set(&db, 1, "wonderland1") .await .unwrap(); // Anonymous users cannot see the loans. let (status, _) = call(&db, "GET", "/loans", None, Value::Null).await; assert_eq!(status, 401); // Alice signs in, borrows the book, then gives it back. let (status, tokens) = call(&db, "POST", "/token", None, json!({"username": "alice", "password": "wonderland1"})).await; assert_eq!(status, 200); let token = tokens["access"].as_str().unwrap(); let (status, loan) = call(&db, "POST", "/loans", Some(token), json!({"book": 1})).await; assert_eq!(status, 201, "{loan}"); assert_eq!(loan["returned_on"], Value::Null); let uri = format!("/loans/{}/give_back", loan["id"]); let (status, loan) = call(&db, "POST", &uri, Some(token), Value::Null).await; assert_eq!(status, 200, "{loan}"); assert!(loan["returned_on"].is_string()); } }
A few remarks:
fresh_schemaanswersNonewhenRIND_TEST_DATABASE_URLis not set, and the test returns early: it is skipped, and passes.- The password is set by the plugin's rules (
passwords(..).set), with its iterations. The test runs withRIND_AUTH_ITERATIONS=1000instead of more than a million: it does not need a strong hash, and it is much faster. callis the small helper that DRF gives you asAPIClient. Write it once in your project, in atests/common/mod.rs, and reuse it.
cargo test does not read .env, and our app() needs
RIND_JWT_SECRET. Export the file's variables first:
set -a; . ./.env; set +a
RIND_AUTH_ITERATIONS=1000 cargo test -p app
running 1 test
.
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Watch out: without
RIND_TEST_DATABASE_URL, the tests that need a database are skipped and pass. Your continuous integration must set it.
What you have built
In six parts, you have:
- a project of two domains, cut into crates;
- three models, and their migrations as plain SQL;
- three resources, with serializers, inputs, nested objects and counts;
- filters, a search without accents, an ordering and pages;
- users who sign in with tokens, rules, and a permission mode;
- a hook that checks a write, an action, and a test over HTTP.
Where to go next
- The topic guides take each subject in depth: every column type, every query, every option of a serializer.
- The railway, the sample application of the repository, uses nearly every feature of rind. Its code is the best reference after this book.
- rind for Django developers maps Django's names to rind's, when you look for "the rind way" of something you know.
- Plugins add health checks, metrics, a cache, mail, background jobs, files and images.