From f4b066b4874e207204ec7c5ae65378f2934a7406 Mon Sep 17 00:00:00 2001 From: LukeMathWalker Date: Mon, 8 Mar 2021 21:10:59 +0000 Subject: [PATCH] Red test. --- tests/api/helpers.rs | 8 ++++++++ tests/api/subscriptions.rs | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/tests/api/helpers.rs b/tests/api/helpers.rs index 29cc2f9..dfe0e5f 100644 --- a/tests/api/helpers.rs +++ b/tests/api/helpers.rs @@ -1,5 +1,6 @@ use sqlx::{Connection, Executor, PgConnection, PgPool}; use uuid::Uuid; +use wiremock::MockServer; use zero2prod::configuration::{get_configuration, DatabaseSettings}; use zero2prod::startup::{get_connection_pool, Application}; use zero2prod::telemetry::{get_subscriber, init_subscriber}; @@ -16,6 +17,7 @@ lazy_static::lazy_static! { pub struct TestApp { pub address: String, pub db_pool: PgPool, + pub email_server: MockServer, } impl TestApp { @@ -31,6 +33,9 @@ impl TestApp { } pub async fn spawn_app() -> TestApp { + // Launch a mock server to stand in for Postmark's API + let email_server = MockServer::start().await; + // Randomise configuration to ensure test isolation let configuration = { let mut c = get_configuration().expect("Failed to read configuration."); @@ -38,6 +43,8 @@ pub async fn spawn_app() -> TestApp { c.database.database_name = Uuid::new_v4().to_string(); // Use a random OS port c.application.port = 0; + // Use the mock server as email API + c.email_client.base_url = email_server.uri(); c }; @@ -56,6 +63,7 @@ pub async fn spawn_app() -> TestApp { db_pool: get_connection_pool(&configuration.database) .await .expect("Failed to connect to the database"), + email_server, } } diff --git a/tests/api/subscriptions.rs b/tests/api/subscriptions.rs index e866dc3..b652f5c 100644 --- a/tests/api/subscriptions.rs +++ b/tests/api/subscriptions.rs @@ -1,4 +1,6 @@ use crate::helpers::spawn_app; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, ResponseTemplate}; #[actix_rt::test] async fn subscribe_returns_a_200_for_valid_form_data() { @@ -21,6 +23,26 @@ async fn subscribe_returns_a_200_for_valid_form_data() { assert_eq!(saved.name, "le guin"); } +#[actix_rt::test] +async fn subscribe_sends_a_confirmation_email_for_valid_data() { + // Arrange + let app = spawn_app().await; + let body = "name=le%20guin&email=ursula_le_guin%40gmail.com"; + + Mock::given(path("/email")) + .and(method("POST")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&app.email_server) + .await; + + // Act + app.post_subscriptions(body.into()).await; + + // Assert + // Mock asserts on drop +} + #[actix_rt::test] async fn subscribe_returns_a_400_when_data_is_missing() { // Arrange