Test database setup

Learn how to set up a separate Postgres test database for Axum handler tests, run migrations before tests, and keep test data away from development data

A test database is a Postgres database that exists only for tests. It holds the same tables as the development database, it is filled and emptied by test code, and nothing in it matters if it is deleted. The application connects to it through a different connection string, so a test that inserts rows, deletes rows, or breaks a constraint can never touch the data the developer works with by hand.

Where This Fits

The test files so far sent requests to a router that held no real data. A handler that reads from Postgres needs a database behind it before its test can run, and that database has to be ready before the first assertion. This page builds that ready state. It creates the database, gives the tests a connection string, runs the migration that creates the users table, and hands each test a pool it can use.

Think of a rehearsal room next to a stage. The play is the same, the actors are the same, and the lines are the same, but the rehearsal room has its own set and its own props. A dropped prop in rehearsal never breaks the set on stage. The test database is the rehearsal room, and the development database is the stage.

The Smallest Working Version

Start with a fresh database named ch19_tests. The name marks it as belonging to this work, and it is separate from any development database. Create it with psql, the command-line tool for talking to Postgres, or with the createdb command. Both do the same job, and the psql form shows the SQL that runs.

psql "postgres://postgres@127.0.0.1:5432/postgres" -c "CREATE DATABASE ch19_tests OWNER axumdocs;"

The command connects to the postgres database, which always exists, and asks it to create the new database. The owner axumdocs is the database user the tests connect as. A user that only reads and writes tables cannot create the extra databases a later page needs, so give this user the right to create databases as well.

psql "postgres://postgres@127.0.0.1:5432/postgres" -c "ALTER ROLE axumdocs CREATEDB;"

If the role does not exist yet, create it first with a password. The password here is a local development password, and it never leaves this machine.

psql "postgres://postgres@127.0.0.1:5432/postgres" -c "CREATE ROLE axumdocs LOGIN PASSWORD 'axumdocs' CREATEDB;"

A Test Database Needs Its Own Name:

Never point tests at the development database. A test that deletes rows to clean up after itself will delete real development rows too, and a test that runs twice will fail on the unique email constraint because the first run already inserted that email. A separate database makes both problems disappear, because the test database holds only test rows.

The connection string for the test database is the address the Rust code uses. It names the user, the password, the host, the port, and the database.

postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests

Read it from left to right. The scheme postgres:// says this is a Postgres connection string. Then comes the user axumdocs, a colon, and the password axumdocs. After the @ comes the host 127.0.0.1, which means this computer, and the port 5432, the port Postgres listens on. After the slash comes the database name ch19_tests. Change any one part and the connection goes somewhere else, so keep this string in one place and reuse it.

The table comes from the migration file the project already has. A migration is a SQL file that describes one change to the schema, and the file name starts with a number so the files run in order.

migrations/0001_create_users.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

This is the same users table the handlers use. The id is assigned by the database, the name and email must be present, the email must be unique, and the timestamp is filled in when the row is created. A test database with a different table shape would test the wrong thing, so the migration file is shared between the application and the tests instead of copied.

The pool module connects to the database and runs the migrations. It needs the migrate feature on sqlx, because the migrate! macro only exists when that feature is turned on.

src/db.rs
use sqlx::{PgPool, migrate::Migrator, postgres::PgPoolOptions};

pub static MIGRATOR: Migrator = sqlx::migrate!();

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}

pub async fn setup_test_pool(database_url: &str) -> PgPool {
    let pool = create_pool(database_url)
        .await
        .expect("could not connect to the test database");
    MIGRATOR
        .run(&pool)
        .await
        .expect("could not run test migrations");
    pool
}

The MIGRATOR static holds the list of migration files, baked into the program at compile time by sqlx::migrate!(). With no argument it looks for a folder named migrations next to Cargo.toml. The setup_test_pool helper does two jobs in order. It connects, and then it runs any migration the database has not seen yet. A test that calls this helper starts with a pool and a ready table, and it never has to think about migrations again.

The project needs these dependencies. The sqlx line carries five features, and each one earns its place.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

The runtime-tokio feature runs sqlx on the Tokio runtime, postgres adds the Postgres driver, macros turns on the query macros, derive turns on the FromRow derive, and migrate turns on the migration macro and runner. The tower dev-dependency is only for the request tests on later pages.

The smallest test proves the setup works. It connects, runs the migrations, and counts the rows in the users table.

tests/db_setup.rs
use axum_project::db::setup_test_pool;

const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";

#[tokio::test]
async fn test_database_setup_creates_users_table() {
    let pool = setup_test_pool(TEST_DATABASE_URL).await;
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .expect("users table must exist after migrations run");
    assert!(count >= 0);
}

The tests on this page read the connection string from the constant at the top of the file, so they need no environment variable. Run them with plain cargo test. The query functions here, sqlx::query and sqlx::query_as, are checked when they run, not when they compile. The checked query macros with an exclamation mark, which the handlers use on a later page, are different. Those check their SQL against the live database at compile time, and they need DATABASE_URL set while compiling.

cargo test

The output ends with a pass.

test test_database_setup_creates_users_table ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Working Setup:

If that test passes, the whole chain works. The database exists, the user can connect, the migration created the table, and the pool hands out connections. Every later test in this cluster builds on this one passing line.

Understanding the Setup Piece by Piece

Three parts do the work here, and each one can fail in its own way. The connection string picks the database, the pool opens connections to it, and the migration runner creates the tables. A failure in any one of them stops the test before the first assertion, so it helps to know which part to blame.

The connection string

const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";

A connection string is a single line that holds everything needed to reach a database. The test file keeps it as a constant at the top, so every test in the file uses the same string and a change in one place reaches all of them. Keeping it as a constant also makes the mistake visible. A test that connects to the wrong database fails loudly at the first query, and the constant at the top of the file is the first place to look.

The string names the test database, not the development database. That one difference is the whole point of this page. Everything else in the string, the user, the host, the port, stays the same, because the tests talk to the same Postgres server. Only the database at the end changes.

The pool size

PgPoolOptions::new()
    .max_connections(5)
    .connect(database_url)
    .await

A pool is a set of open connections the program reuses instead of opening a new one for every query. The max_connections(5) call caps the set at five. Five is enough for tests, because a test rarely needs more than one or two connections at the same time, and a small cap keeps a run of parallel tests from opening more connections than Postgres allows. Postgres has a limit on simultaneous connections, and a test run that opens dozens of pools with dozens of connections each can hit it. A small cap in test code is cheap insurance.

The .connect() call opens the first connection and checks that the server answers. If the server is down, or the password is wrong, or the database does not exist, this is where the error appears, wrapped in a Result. The helper turns that Result into a panic with expect, because a test with no database cannot run at all, and a clear panic message beats a confusing failure three lines later.

The migration runner

MIGRATOR
    .run(&pool)
    .await
    .expect("could not run test migrations");

The runner keeps a table named _sqlx_migrations inside the database, and it records every migration it has run. On the first run it creates the users table and records version 1. On the second run it sees version 1 already recorded and runs nothing. That is what makes the helper safe to call at the start of every test. Running the same migration twice would fail with "relation already exists", but the runner never runs it twice.

A common confusion is the order of the two steps. The pool must exist before the migrations can run, because the runner sends SQL through the pool. The helper connects first and migrates second, and that order never changes.

The Concept Behind a Separate Test Database

A test that writes to a database changes shared state. Two tests that share one database can see each other's rows, and the order they run in changes what each one sees. A test that passes alone and fails when run with the full suite is almost always a shared-state problem, and a shared database is the most common form of it.

A separate database fixes the worst version of the problem. Test rows never mix with development rows, and deleting everything in the test database is safe, because nothing in it matters. It does not fix sharing between tests, because the tests still share the one test database with each other. That sharing is handled by the isolation techniques on the later pages, where each test gets its own database or its own rolled-back transaction. The separate database is the floor, not the ceiling. It protects development data, and the later techniques protect tests from each other.

Think of it as separate notebooks for homework and for class notes. Writing homework in the class notebook does not ruin the notes at once, but one careless page torn out takes notes with it. Two notebooks cost nothing and remove the risk entirely.

Why the Setup Helper Lives in the Library

The setup_test_pool helper sits in src/db.rs, next to create_pool, instead of being copied into every test file. The reason is the same reason the application keeps its pool code in one place. One copy means one place to change the pool size, one place to change the migration call, and one place where a mistake can hide.

Test files are part of the project, and they import from the library crate with use axum_project::db::setup_test_pool;. That import only works because the code lives in src/lib.rs modules, not in src/main.rs. Code in main.rs belongs to the binary and cannot be imported by tests. Code in lib.rs belongs to the library and can be imported by anything, including the test files. The split between lib.rs and main.rs is what makes the helper reachable.

A Richer Complete Example

The smallest test only counted rows. A realistic setup test also writes a row and reads it back, because a table that exists but refuses inserts is not a working setup. This test inserts one user, reads the name back by id, and deletes the row when it is done.

tests/db_setup.rs
use axum_project::db::setup_test_pool;

const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";

#[tokio::test]
async fn test_database_setup_insert_and_read_back() {
    let pool = setup_test_pool(TEST_DATABASE_URL).await;
    sqlx::query("DELETE FROM users WHERE email = 't10-asha@example.com'")
        .execute(&pool)
        .await
        .unwrap();
    let (id,): (i32,) = sqlx::query_as(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id",
    )
    .bind("Asha")
    .bind("t10-asha@example.com")
    .fetch_one(&pool)
    .await
    .expect("insert must succeed in the test database");
    let (name,): (String,) = sqlx::query_as("SELECT name FROM users WHERE id = $1")
        .bind(id)
        .fetch_one(&pool)
        .await
        .expect("inserted row must be readable");
    assert_eq!(name, "Asha");
    sqlx::query("DELETE FROM users WHERE id = $1")
        .bind(id)
        .execute(&pool)
        .await
        .unwrap();
}

The test deletes any row with the same email before it starts, so a leftover row from an earlier run cannot break the unique email constraint. It deletes the row it created at the end, so the next run starts clean. The RETURNING id clause hands back the id Postgres assigned, and the test uses that id for the read, instead of guessing that the id is 1. Guessing an id works once and breaks the second time the test runs, because the sequence keeps counting up.

The two tests together prove the setup end to end. The first proves the table exists. The second proves rows can be written and read. Run both with the same command as before.

cargo test --test db_setup

The output shows both passing.

test test_database_setup_creates_users_table ... ok
test test_database_setup_insert_and_read_back ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Setting the Connection String with an Env File

Some parts of sqlx read the connection string from the environment instead of from code. The checked query macros read it at compile time, and the test macro on the next page reads it at test time. Both look in a .env file in the project root when the variable is not exported, so the file supplies the value without a long command. The tests on this page read the constant instead, so they do not need the file yet, but the project will need it once the handlers use the checked macros. The file has one line.

.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests

With the file in place, cargo test works with no prefix, because the test process reads the file when it starts. The same file feeds the query macros at compile time, which is why the macros can check SQL against the live database without an exported variable.

Never Commit the Env File:

A .env file holds a password, even a local one. Add .env to .gitignore before the first commit, and never push it to a shared repository. A password that reaches a public repository has to be treated as known to everyone, and changing it means changing every place that used it.

The .gitignore entry is one line.

.gitignore
.env

A teammate who clones the project copies .env.example instead, a file with the same keys and placeholder values, and fills in their own password. The example file is safe to commit because it holds no real secret.

.env.example
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests

Checking the Database by Hand

Tests are not the only way to look at the test database. The psql command opens a session, and a few commands show whether the setup matches what the tests expect.

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" -c "\d users"

The \d users command describes the table, listing the four columns, their types, and their defaults. The output shows the id with its sequence default, the name and email as text that must not be null, and created_at with its now() default.

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" -c "SELECT COUNT(*) FROM users;"

The count query shows how many rows the tests left behind. A test database with rows in it after a run is normal when tests clean up only their own rows. A count that keeps growing run after run means some test inserts without deleting, and that test will eventually collide with another test on the unique email constraint.

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" -c "DROP DATABASE ch19_tests;"

Deleting the database and recreating it is the fastest way to recover from a messed-up test database. The migrations rebuild the tables on the next test run, so nothing is lost except test rows. This only works because the database holds nothing of value, which is the whole reason it exists.

How the Setup Fits Together

The pieces connect in a fixed order, and each one depends on the one before it.

Postgres server running on 127.0.0.1:5432
        |
        v
Database ch19_tests created, owned by axumdocs
        |
        v
DATABASE_URL names ch19_tests in .env
        |
        v
create_pool opens up to 5 connections
        |
        v
MIGRATOR runs 0001_create_users.sql once
        |
        v
Test receives a pool with a ready users table

A failure at any step has a distinct error. A refused connection means the server is not running or the port is wrong. A password error means the user or password in the string is wrong. A "database does not exist" error means the create step was skipped. A "relation already exists" error means the table was created by hand and the migration runner was not told, which happens when the table is made with psql instead of through the migration. The fix for that last one is to drop the hand-made table and let the migration create it, or to record the migration as applied in the _sqlx_migrations table.

Testing the Setup

The test file for this page is the one shown above, with both tests in tests/db_setup.rs. The file name matters. Files under tests/ are integration tests, and each file compiles into its own test binary. A file named db_setup.rs runs with cargo test --test db_setup, and its tests run in parallel with each other by default.

The tower dev-dependency is not used on this page, and the handler code is not used either. This page only proves the database is reachable and the table works. The handlers join the tests on the later pages, where the same pool and the same helper appear again unchanged.

Common Beginner Mistakes

Testing against the development database

// Wrong - this is the development database, not the test database
const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/axum_dev";

A test run against the development database deletes development rows, inserts test rows with confusing names, and fails on the second run when the unique email already exists. The fix is a database name that says test in it, and a habit of reading the last part of the connection string before running tests.

Forgetting to run migrations in the test

// Wrong - the pool connects, but the users table may not exist
let pool = create_pool(TEST_DATABASE_URL).await.unwrap();

A fresh database has no tables. The first query fails with "relation users does not exist", and the error looks like a code problem when it is really a setup problem. The fix is the helper, which runs the migrations right after connecting, so no test can forget the step.

Hardcoding the connection string in every test

// Wrong - the same string copied into ten tests
let pool = setup_test_pool("postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests").await;

Ten copies of the string mean ten places to update when the password or the database name changes, and one of them will be missed. The fix is the constant at the top of the file, or the .env file, so the string lives in exactly one place per project.

Creating the table by hand instead of through the migration

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" -c "CREATE TABLE users (...);"

A hand-made table works for the first test run, and then the migration runner fails on the second run, because it tries to create a table that already exists and the runner has no record of having run it. The fix is to let the migration create the table, and to use psql only for creating the database itself, which no migration can do.

Migrations Cannot Create Their Own Database:

A migration runs inside a database, so it cannot create that database. The database must exist before the first migration runs. That is why the setup has two steps in two different tools. The database is created with psql or createdb, and everything inside it is created by migrations.

Setting a large pool size for tests

// Wrong - far more connections than tests need
PgPoolOptions::new().max_connections(50)

Fifty connections per pool, times several test binaries running at once, can pass the server limit and make tests fail with connection errors that look random. The fix is the small cap of five, which is more than a single test file needs.

Final Complete Example

Everything on this page put together is one project. The migration creates the table, the pool module connects and migrates, and the test file proves both work.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
migrations/0001_create_users.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
src/db.rs
use sqlx::{PgPool, migrate::Migrator, postgres::PgPoolOptions};

pub static MIGRATOR: Migrator = sqlx::migrate!();

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}

pub async fn setup_test_pool(database_url: &str) -> PgPool {
    let pool = create_pool(database_url)
        .await
        .expect("could not connect to the test database");
    MIGRATOR
        .run(&pool)
        .await
        .expect("could not run test migrations");
    pool
}
src/lib.rs
pub mod db;
tests/db_setup.rs
use axum_project::db::setup_test_pool;

const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";

#[tokio::test]
async fn test_database_setup_creates_users_table() {
    let pool = setup_test_pool(TEST_DATABASE_URL).await;
    let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .expect("users table must exist after migrations run");
    assert!(count >= 0);
}

#[tokio::test]
async fn test_database_setup_insert_and_read_back() {
    let pool = setup_test_pool(TEST_DATABASE_URL).await;
    sqlx::query("DELETE FROM users WHERE email = 't10-asha@example.com'")
        .execute(&pool)
        .await
        .unwrap();
    let (id,): (i32,) = sqlx::query_as(
        "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id",
    )
    .bind("Asha")
    .bind("t10-asha@example.com")
    .fetch_one(&pool)
    .await
    .expect("insert must succeed in the test database");
    let (name,): (String,) = sqlx::query_as("SELECT name FROM users WHERE id = $1")
        .bind(id)
        .fetch_one(&pool)
        .await
        .expect("inserted row must be readable");
    assert_eq!(name, "Asha");
    sqlx::query("DELETE FROM users WHERE id = $1")
        .bind(id)
        .execute(&pool)
        .await
        .unwrap();
}

Run the tests with plain cargo test. The tests on this page read the connection string from the constant, so no environment variable is needed.

cargo test --test db_setup

Both tests pass, and the database is ready for the handler tests that come after it.

Summary

The setup on this page is three decisions that stay fixed for the rest of the work. A database that exists only for tests, a connection string that names it and lives in one place, and a helper that connects and runs migrations before any test touches a table. Those three decisions are what make every later test honest, because a test that runs against the wrong database or a missing table proves nothing about the handler.

The single most useful habit from this page is to read the database name at the end of the connection string before running tests. The name is the difference between a rehearsal and a live performance, and the habit takes one second. The decision framework is plain. If a test writes rows, it needs its own database. If it only reads fixed data, it still needs its own database, because a later test will write. Give the tests their own database from the start, and the isolation work on the later pages has something solid to stand on.