zero-to-axum/tests/subscriptions.rs
2025-07-16 10:04:59 -05:00

60 lines
1.5 KiB
Rust

pub mod fixture;
use fixture::TestServer;
use anyhow::Result;
use maik::MailAssertion;
use regex::bytes::Regex;
use test_log::test as traced;
#[traced(tokio::test)]
async fn subscribe_succeeds_with_valid_input() -> Result<()> {
let server = TestServer::spawn().await;
let client = reqwest::Client::builder().build()?;
// Subscribe
let resp = client
.post(server.url("/subscriptions"))
.header("Content-Type", "application/x-www-form-urlencoded")
.body("name=le%20guin&email=ursula_le_guin%40gmail.com")
.send()
.await?;
assert_eq!(resp.status(), 200, "subscribe succeeds");
assert!(
server
.mock_smtp_server
.assert(MailAssertion::new().body_matches(Regex::new(r"example\.com")?)),
"email sent has link"
);
server.shutdown().await
}
#[traced(tokio::test)]
async fn subscribe_fails_with_missing_data() -> Result<()> {
let server = TestServer::spawn().await;
let client = reqwest::Client::new();
let test_cases = [
("", "missing both name and email"),
("name=le%20guin", "missing the email"),
];
for (body, msg) in test_cases {
let resp = client
.post(server.url("/subscriptions"))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await?;
assert_eq!(
resp.status(),
422,
"subscribe fails with bad request when {msg}"
);
}
server.shutdown().await
}