|
| 1 | +use reqwest::StatusCode; |
| 2 | +use serde::Serialize; |
| 3 | + |
| 4 | +use crate::helpers::spawn_app; |
| 5 | + |
| 6 | +#[derive(Serialize)] |
| 7 | +struct Subscription { |
| 8 | + name: Option<String>, |
| 9 | + email: Option<String>, |
| 10 | +} |
| 11 | + |
| 12 | +#[tokio::test] |
| 13 | +async fn subscribe_returns_a_200_for_valid_form_data() { |
| 14 | + let app = spawn_app().await; |
| 15 | + let client = reqwest::Client::new(); |
| 16 | + |
| 17 | + let sub = Subscription { |
| 18 | + name: Some("vla".to_string()), |
| 19 | + email: Some("vla@example.com".to_string()), |
| 20 | + }; |
| 21 | + |
| 22 | + let resp = client |
| 23 | + .post(&format!("{}/subscriptions", &app.host)) |
| 24 | + .form(&sub) |
| 25 | + .send() |
| 26 | + .await |
| 27 | + .expect("failed to execute request"); |
| 28 | + |
| 29 | + assert_eq!(StatusCode::OK, resp.status()); |
| 30 | + |
| 31 | + let saved = sqlx::query!("select email, name from subscriptions") |
| 32 | + .fetch_one(&app.pg_pool) |
| 33 | + .await |
| 34 | + .expect("failed to fetch saved subscription"); |
| 35 | + |
| 36 | + assert_eq!(saved.name, sub.name); |
| 37 | + assert_eq!(saved.email, sub.email); |
| 38 | +} |
| 39 | + |
| 40 | +#[tokio::test] |
| 41 | +async fn subscribe_returns_a_400() { |
| 42 | + let app = spawn_app().await; |
| 43 | + let client = reqwest::Client::new(); |
| 44 | + let test_cases = vec![ |
| 45 | + ( |
| 46 | + "Missing email", |
| 47 | + Subscription { |
| 48 | + name: Some("vla".to_string()), |
| 49 | + email: None, |
| 50 | + }, |
| 51 | + ), |
| 52 | + ( |
| 53 | + "Missing name", |
| 54 | + Subscription { |
| 55 | + name: None, |
| 56 | + email: Some("vla@example.com".to_string()), |
| 57 | + }, |
| 58 | + ), |
| 59 | + ( |
| 60 | + "Missing whole data", |
| 61 | + Subscription { |
| 62 | + name: None, |
| 63 | + email: None, |
| 64 | + }, |
| 65 | + ), |
| 66 | + ( |
| 67 | + "Empty email", |
| 68 | + Subscription { |
| 69 | + name: Some("vla".to_string()), |
| 70 | + email: Some("".to_string()), |
| 71 | + }, |
| 72 | + ), |
| 73 | + ( |
| 74 | + "Empty name", |
| 75 | + Subscription { |
| 76 | + name: Some("".to_string()), |
| 77 | + email: Some("vla@example.com".to_string()), |
| 78 | + }, |
| 79 | + ), |
| 80 | + ( |
| 81 | + "Invalid email", |
| 82 | + Subscription { |
| 83 | + name: Some("vla".to_string()), |
| 84 | + email: Some("vla-example.com".to_string()), |
| 85 | + }, |
| 86 | + ), |
| 87 | + ]; |
| 88 | + |
| 89 | + for (name, input) in test_cases { |
| 90 | + let resp = client |
| 91 | + .post(&format!("{}/subscriptions", &app.host)) |
| 92 | + .form(&input) |
| 93 | + .send() |
| 94 | + .await |
| 95 | + .expect("failed to execute request"); |
| 96 | + |
| 97 | + assert_eq!(StatusCode::BAD_REQUEST, resp.status(), "case name {}", name); |
| 98 | + } |
| 99 | +} |
0 commit comments