Skip to content

Test backend behavior ​

rxferrix::testing::TestApp opens a fresh temporary data directory and runs the registered backend functions in-process. Use it to test validation, access checks, transactions, and delayed work without a separate server.

Configure the app in one place ​

Put the app's configuration in a function marked #[rxferrix::app]. main runs it, and every test gets an app built from it, with the same auth methods, crons, guard and storage limits. Nothing leaves a test: emails go to the dev mailer (AuthConfig::dev_mailer when set, else the log) instead of a configured SMTP server or mailer, and files stay in the test's temporary directory:

rust
// src/app.rs
use rxferrix::RxFerrix;
use rxferrix::auth::AuthConfig;

#[rxferrix::app]
pub fn configure() -> RxFerrix {
    RxFerrix::new().auth(AuthConfig::password())
}
rust
// src/main.rs
mod app;
mod tasks;
#[cfg(test)]
mod tests;

fn main() -> rxferrix::Result<()> {
    app::configure().run()
}

Apps created with rxferrix new start this way. A binary has one #[rxferrix::app] function.

Call typed functions ​

For the starter app's tasks module:

rust
// src/tests.rs
use rxferrix::testing::*;

use crate::tasks;

#[rxferrix::test]
async fn adding_a_task(t: TestApp) {
    let id = t.mutation::<tasks::add>("Buy milk".to_string()).await.unwrap();
    let all = t.query::<tasks::list>(()).await.unwrap();
    assert_eq!(all[0].id, id);
    assert_eq!(all[0].text, "Buy milk");

    let err = t.mutation::<tasks::add>(String::new()).await.assert_user_error("empty_text");
    assert_eq!(err.message, "A task needs some text");
}

#[rxferrix::test] makes a test that runs on its own runtime: the app needs no Tokio dependency. A test may return rxferrix::Result<()> to use ?, and #[ignore] and #[should_panic] work as usual (a panic while setting up the app still fails a #[should_panic] test: only the body's panic counts). .assert_user_error("code") checks that a call failed with that user error and returns it; it fails the test on success, on another code, or on any other error.

This uses the generated starter's no-argument list. If you added the guide's optional filter argument, pass None::<bool> instead of ().

Arguments follow function parameter order: () for none, a value or (value,) for one, and a tuple for several. Results have their Rust types; inspect .id on a Doc<T> rather than the client's _id.

Outside #[rxferrix::test], TestApp::configured(app::configure()).await? builds the same app, and TestApp::new() a bare one, with no auth configuration, crons or guard. Use them in a #[tokio::test] (add Tokio as a development dependency with the macros and rt features).

Test as an app user ​

rust
let ann = t.create_user("ann@example.com", None).await.unwrap();
let result = t.as_user(ann).query::<crate::notes::list>(()).await.unwrap();

create_user creates a verified user directly; it does not require a configured sign-in method or email delivery. Pass Some(password) when a test needs a password account.

Test both allowed and refused calls, including signed-out callers and another user's document IDs. A guard set in configure applies to as_user calls in a #[rxferrix::test]; with TestApp::with_options, set AppOptions::guard. The chat example's tests show membership and ownership checks.

Advance jobs without sleeping ​

The scheduler does not run automatically in a TestApp. Crons from configure are registered, and run when they become due; a TestApp::new() has none. t.run_due_jobs().await? runs due work; t.advance_time(Duration::from_secs(60)).await? advances the test clock and runs work that becomes due.

Use these helpers for delays, expiry, crons, and retries. For code that truly requires a background scheduler, opt in with start_scheduler().

Set environment variables ​

A function that reads ctx.env sees nothing in a fresh test app. Set values with rxferrix::env::put, the internal mutation behind the env set command:

rust
t.mutation::<rxferrix::env::put>(("RATES_URL".to_string(), Some(url))).await?;

None removes the variable. The call returns whether anything changed.

Read sent emails ​

Tests send email to the dev mailer (see above). To read it, give the test build a MemoryMailer as its dev mailer:

rust
// src/app.rs
use rxferrix::RxFerrix;
use rxferrix::auth::AuthConfig;

#[cfg(test)]
pub static INBOX: std::sync::LazyLock<std::sync::Arc<rxferrix::auth::MemoryMailer>> =
    std::sync::LazyLock::new(rxferrix::auth::MemoryMailer::new);

#[rxferrix::app]
pub fn configure() -> RxFerrix {
    let auth = AuthConfig::password().magic_link();
    #[cfg(test)]
    let auth = auth.dev_mailer(INBOX.clone());
    RxFerrix::new().auth(auth)
}

The #[cfg(test)] keeps serve --dev printing codes to the log. In a test of the send_confirmation action:

rust
t.action::<crate::emails::send_confirmation>(("ann@example.com".to_string(), "See you at 10".to_string())).await?;
let email = crate::app::INBOX.last_to("ann@example.com").expect("an email to Ann");
assert_eq!(email.subject, "Your booking");

An Email has to, subject, body, and html; emails() returns every one sent so far. The inbox is shared by the tests of the binary, which run in parallel, so give each test its own address and look emails up with last_to. An action's ctx.send_email has sent when the call returns. Auth emails with codes and links go out in the background: poll last_to, waiting with tokio::time::sleep(..).await between tries (a test runs on a single-threaded runtime, so std::thread::sleep would keep the email from being sent; add tokio with the time feature as a development dependency). For an auth-only test, TestApp::with_auth(AuthConfig::password().mailer(mailer.clone())) keeps the mailer, but it doesn't run configure.

Fake an external service ​

Keep the address of a service an action calls in ctx.env, as in Use an action for external work. A test can then start a small server on a free local port and point the variable at it. This tests the guide's fetch_rate action. Add axum and tokio as development dependencies:

toml
[dev-dependencies]
axum = "0.8"
tokio = { version = "1", features = ["net", "rt"] }
rust
#[rxferrix::test]
async fn reads_the_rate(t: TestApp) -> rxferrix::Result<()> {
    let service = axum::Router::new()
        .route("/rates/EUR", axum::routing::get(|| async { r#"{ "rate": 1.08 }"# }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let url = format!("http://{}", listener.local_addr()?);
    tokio::spawn(async move { axum::serve(listener, service).await });

    t.mutation::<rxferrix::env::put>(("RATES_URL".to_string(), Some(url))).await?;
    assert_eq!(t.action::<crate::rates::fetch_rate>("EUR".to_string()).await?, 1.08);
    Ok(())
}

Test a migration ​

t.app().run_migration::<f>(RunOptions::default()) runs a migration over the test's data and returns a report with outcome, processed, and changed. RunOptions { dry_run: true, ..Default::default() } reports without writing. For a migration add_priority over the tasks a test created:

rust
use rxferrix::migrations::{RunOptions, RunOutcome};

let report = t.app().run_migration::<crate::tasks::add_priority>(RunOptions::default()).await?;
assert_eq!(report.outcome, RunOutcome::Completed);

Writes are checked against the current table type, so a test can't store documents in an older shape, such as ones missing a field the type now requires. Test that kind of transformation without the database. An on_read migration is a plain function of the stored JSON, so call it directly: tags_from_tag(&json!({ "title": "a", "tag": "x" })) (declare it pub(crate) to reach it from the tests module). For a batch migration, put the transformation in a helper that takes and returns serde_json::Value, and test the helper.

Exercise restarts and HTTP ​

HelperPurpose
TestApp::configured(builder)The app as a RxFerrix builder configures it (what #[rxferrix::test] uses).
TestApp::with_options(AppOptions { ... })Configure runtime options, guards, and services.
TestApp::with_auth(config)Configure sign-in behavior for auth tests.
t.restart().await?Reopen the same data directory and check persisted state.
t.serve().await?Start HTTP and WebSocket handling on an available local port.
t.query_run::<f>(args)Inspect a query run and its tracked reads.
t.mutation_ts::<f>(args)Get a mutation result and commit timestamp.
t.app()Access the lower-level runtime.

#[rxferrix::test], TestApp::new(), configured() and with_auth() enable development mode, including detailed errors and dev-only functions. with_options() uses the options you supply, so set dev: true when that is what the test needs. For JavaScript binding tests, @rxferrix/client/testing provides a fake sync server; the client packages use it in their test suites.