zero-to-production/tests/api/subscriptions.rs

72 lines
2 KiB
Rust
Raw Normal View History

2021-02-14 15:26:43 +00:00
use crate::helpers::spawn_app;
2021-02-14 12:24:50 +00:00
#[tokio::test]
2021-02-14 12:24:50 +00:00
async fn subscribe_returns_a_200_for_valid_form_data() {
// Arrange
2021-02-14 15:26:43 +00:00
let app = spawn_app().await;
2021-02-14 12:24:50 +00:00
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
// Act
2021-02-14 17:07:31 +00:00
let response = app.post_subscriptions(body.into()).await;
2021-02-14 12:24:50 +00:00
// Assert
assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions",)
.fetch_one(&app.db_pool)
.await
.expect("Failed to fetch saved subscription.");
assert_eq!(saved.email, "ursula_le_guin@gmail.com");
assert_eq!(saved.name, "le guin");
}
#[tokio::test]
2021-02-14 12:24:50 +00:00
async fn subscribe_returns_a_400_when_data_is_missing() {
// Arrange
2021-02-14 15:26:43 +00:00
let app = spawn_app().await;
2021-02-14 12:24:50 +00:00
let test_cases = vec![
("name=le%20guin", "missing the email"),
("email=ursula_le_guin%40gmail.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
// Act
2021-02-14 17:07:31 +00:00
let response = app.post_subscriptions(invalid_body.into()).await;
2021-02-14 12:24:50 +00:00
// Assert
assert_eq!(
400,
response.status().as_u16(),
// Additional customised error message on test failure
"The API did not fail with 400 Bad Request when the payload was {}.",
error_message
);
}
}
#[tokio::test]
2021-02-14 12:24:50 +00:00
async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
// Arrange
2021-02-14 15:26:43 +00:00
let app = spawn_app().await;
2021-02-14 12:24:50 +00:00
let test_cases = vec![
("name=&email=ursula_le_guin%40gmail.com", "empty name"),
("name=Ursula&email=", "empty email"),
("name=Ursula&email=definitely-not-an-email", "invalid email"),
];
for (body, description) in test_cases {
// Act
2021-02-14 17:07:31 +00:00
let response = app.post_subscriptions(body.into()).await;
2021-02-14 12:24:50 +00:00
// Assert
assert_eq!(
400,
response.status().as_u16(),
"The API did not return a 400 Bad Request when the payload was {}.",
description
);
}
}