Skip to content

Overriding in tests

Seed pinned config values in e2e tests, unit-test a Config on a map of variables, keep both hermetic.

Tests bypass the environment in two ways depending on the layer. End-to-end tests use TestApp and seed pinned config values directly — the seed wins over the factory that would read it. Unit tests for a config read a map of variables through ConfigService::with_vars, and never touch std::env.

Both rely on a single guarantee: under <PREFIX>_ENV=test, the .env.local file is skipped, so a developer’s personal secrets cannot leak in.

TestApp::builder() exposes .provide(value) — when the value’s type is a config a provider injects, or a module’s for_root loads, the seed wins and the factory never runs. The seed still passes what a read value does, before any factory reads it: a duration outside its range or a field its validate() refuses fails the boot with the same ConfigError, naming the field or the namespace.

apps/auth/tests/e2e/token.rs
use auth::{AuthModule, ClientPayload, SignInConfig};
use features::Role;
use nest_rs::oauth::server::{OAuthServerConfig, RegisteredClient};
use nest_rs::testing::TestApp;
use uuid::Uuid;
use crate::harness::basic_auth;
#[tokio::test]
async fn issues_a_token_for_a_registered_client() {
let app = TestApp::builder()
.module::<AuthModule>()
.ephemeral_database::<migrations::Migrator>()
.provide(OAuthServerConfig {
clients: vec![RegisteredClient::new(
"test-client",
"secret",
["posts:read"],
["http://localhost:3002"],
ClientPayload {
org_id: Uuid::nil(),
roles: vec![Role::User],
},
)],
})
.provide(SignInConfig {
resources: vec!["http://localhost:3002".into()],
default_org_id: Uuid::nil(),
..SignInConfig::default()
})
.build()
.await
.unwrap();
let response = app.http().post("/token")
.header("authorization", basic_auth("test-client", "secret"))
.content_type("application/x-www-form-urlencoded")
.body("grant_type=client_credentials")
.send()
.await;
response.assert_status_is_ok();
}

The test never sets a <PREFIX>_OAUTH__SERVER__* or <PREFIX>_SIGN_IN__* variable: the two configs it reads are its seeds. What it still takes from the cascade is the server its throwaway database is created on, <PREFIX>_SEAORM__URL, and the signing key apps/auth/.env.test names. nest_rs::oauth::server takes the umbrella’s oauth-server feature, and TestApp its testing feature, in the suite’s [dev-dependencies].

Every configurable module’s bare import loads its config from the environment over the config’s defaults; its for_root(cfg) makes cfg the base the environment overlays.

apps/api/tests/e2e/http.rs
let app = TestApp::builder()
.module::<ApiModule>()
// ...
.build()
.await?;
apps/api/src/module.rs
use nest_rs::core::module;
use nest_rs::http::{HttpConfig, HttpModule};
#[module(
imports = [
HttpModule::for_root(HttpConfig {
host: "127.0.0.1".into(),
port: 0,
..Default::default()
}),
],
)]
pub struct ApiModule;

HttpModule::for_root(cfg) routes its HttpConfig through ConfigModule::provide_root, which queues the one resolving factory its bare import would — the pin only decides what the environment overlays. Use this when the test module owns the binding (it composes the app) and an ambient <PREFIX>_HTTP__* overriding it is welcome; use .provide() when the value must hold regardless of the environment.

A module’s bare import always reads the default EnvSource. To isolate config loading from std::env entirely, build the ConfigService yourself with a custom source and seed the loaded Config:

crates/features/tests/integration/config.rs
use std::sync::Arc;
use nest_rs::config::{Config, ConfigService, MapSource, var_name};
let source = Arc::new(MapSource::from_iter([
(var_name("seaorm", "URL"), "postgres://test/app"),
(var_name("seaorm", "MAX_CONNECTIONS"), "5"),
]));
let env = ConfigService::with_source("seaorm", source);
let cfg = SeaOrmConfig::from_env(&env, SeaOrmConfig::default()).unwrap();
let app = TestApp::builder()
.module::<ApiModule>()
.provide(cfg)
.build()
.await?;

A custom source also decides where the values come from, so the test cannot pick up a stray <PREFIX>_* from the ambient environment — that is the whole point of reaching for one.

It is not the case that a test leaves std::env untouched. No config read writes there, but TestApp::builder() calls load_project_env, which publishes the project’s .env cascade set-if-absent — the files of the package’s Cargo workspace root, where nestrs run starts the binary, under the package’s own (an app’s own files) — the harness needs backend URLs before any ConfigService exists. The merge is bounded (once per process, real env still wins, and .env.local is skipped under <PREFIX>_ENV=test), and a for_root pin still outranks every cascade value, but a test asserting on a variable a committed .env happens to define will read the file. Use with_source — or .provide(cfg) — when the test must not. See hermeticity and the cascade.

When the unit under test is the mapping itself — which variable each field reads, and what a reader of your own refuses — read it from a map of variables. ConfigService::with_vars answers for one namespace, by key, from the pairs you give it, and reads neither std::env nor the .env cascade. Validation is the struct’s own validate(), which load() runs after the mapping.

crates/features/src/sign_in/config.rs (from the demo, abridged)
#[cfg(test)]
mod tests {
// …
use super::*;
const RESOURCE: &str = "https://api.example.com";
// …
#[test]
fn the_resources_and_the_default_org_are_read_from_their_variables() {
let org = Uuid::now_v7();
let env = ConfigService::with_vars(
"sign_in",
[
(
"RESOURCES",
"https://api.example.com,https://mcp.example.com",
),
("DEFAULT_ORG_ID", &org.to_string()),
],
);
let cfg = SignInConfig::from_env(&env, SignInConfig::default()).expect("parses");
assert_eq!(cfg.resources, [RESOURCE, "https://mcp.example.com"]);
assert_eq!(cfg.default_org_id, org);
cfg.validate().expect("valid");
}
#[test]
fn a_sign_in_naming_no_resource_fails_validation() {
let errors = SignInConfig::default().validate().unwrap_err();
let fields = errors.field_errors();
assert_eq!(fields["resources"][0].code, "at_least_one_resource");
}
// …
}

Nothing in it touches the process, so these tests run in parallel under any runner.

TestApp::builder() sets <PREFIX>_ENV=test if nothing else has set it. Two consequences:

  • The .env cascade skips .env.local (per-machine secrets stay out of the test).
  • The development conveniences the framework keys on the profile are on, as in development: the OpenAPI documentation serves /api, the GraphQL playground mounts and introspection answers, Server-Timing stamps its header, and storage allows plain HTTP. The emit of a committed artifact — the SDL, the OpenAPI document — waits for development alone, so parallel suites never rewrite a committed file. No profile names a database, a Redis or a store: .env.test does.

A test that wants to assert prod behavior overrides this explicitly before building the app — unsafe { std::env::set_var("<PREFIX>_ENV", "production") }. Set it before TestApp::builder() so the cascade loads the right files.

  • Don’t mutate std::env to feed a config. std::env::set_var is unsafe since Rust 2024: in a process another test shares, it races that test’s reads. with_vars answers from a map, and .provide() skips the read altogether.
  • Don’t pin config in a setup shared between tests. Each test should declare its inputs explicitly — that’s what makes a failure reproducible from the test code alone.
  • Don’t put a deployment’s secret in .env.test. The file is committed: treat it as documentation of test defaults, not as a vault. What it holds opens nothing outside a test run — the HS256 key nestrs g auth draws into it signs only the tokens your suites send.