sqlx-testcontainers
sqlx-testcontainers is a Rust library that simplifies integration testing with sqlx and testcontainers-rs. It provides a procedural macro #[sqlx_testcontainers::test] that automatically:
- Starts a temporary PostgreSQL container using Testcontainers.
- Connects to the container and runs your database migrations.
- Provides an active
sqlx::PgConnectiondirectly to your test function. - Cleans up the container after the test finishes.
Features
- Zero-Config Database Tests: No need to manually manage database instances or connection strings for tests.
- Automatic Migrations: Uses
sqlx::migrate!()to ensure your test database schema is up-to-date. - Isolated Environments: Every test gets its own fresh container, ensuring no cross-test interference.
- Customizable Images: Easily specify PostgreSQL versions/tags.
Installation
Add this to your Cargo.toml:
[]
= { = "https://github.com/anthonysuper/sqlx-testcontainers" }
= { = "0.8", = ["postgres", "runtime-tokio-rustls", "migrate"] }
= { = "1", = ["full"] }
Usage
Simply replace #[tokio::test] with #[sqlx_testcontainers::test] and add a PgConnection argument to your test function.
use Row;
async
async
async
Requirements
- Docker: Since this uses Testcontainers, you must have Docker (or a compatible container runtime) installed and running in your environment.
- SQLx Migrations: By default, it looks for a
migrations/folder in your project root to apply to the test database.
License
MIT or Apache-2.0.