From 6db0a7bc86ba8bb30edcb2126ebcabcb65c340d5 Mon Sep 17 00:00:00 2001 From: Nick Bland Date: Sun, 7 Nov 2021 00:23:49 +1000 Subject: [PATCH] implement test changes regarding database also added .env for database connection details (used by sqlx) --- .env | 1 + src/configuration.rs | 9 +++++++++ tests/health_check.rs | 17 +++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 .env diff --git a/.env b/.env new file mode 100644 index 0000000..ff74813 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DATABASE_URL="postgres://postgres:password@localhost:5432/newsletter" \ No newline at end of file diff --git a/src/configuration.rs b/src/configuration.rs index fffa827..85f9b9f 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -22,4 +22,13 @@ pub fn get_configuration() -> Result { // Try convert into Settings type settings.try_into() +} + +impl DatabaseSettings { + pub fn connection_string(&self) -> String { + format!( + "postgres://{}:{}@{}:{}/{}", + self.username, self.password, self.host, self.port, self.database_name + ) + } } \ No newline at end of file diff --git a/tests/health_check.rs b/tests/health_check.rs index fbc94c6..2dbbf47 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,6 +1,9 @@ use std::net::TcpListener; use mail_app::startup::run; +use sqlx::{PgConnection, Connection}; +use mail_app::configuration::get_configuration; + // Create new instance of the application on a random port and return address [`http://localhost:XXXX`] fn spawn_app() -> String { let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port"); @@ -36,6 +39,12 @@ async fn health_check_works() { async fn subscribe_returns_200_for_valid_form_data() { // Arrange let app_address = spawn_app(); + let configuration = get_configuration().expect("Failed to read configuration."); + let connection_string = configuration.database.connection_string(); + // Connection trait MUST be in scope to invoke. + let mut connection = PgConnection::connect(&connection_string) + .await + .expect("Failed to connect to Postgres."); let client = reqwest::Client::new(); let body = "name=le%20guin&email=usrula_le_guin%40gmail.com"; @@ -50,6 +59,14 @@ async fn subscribe_returns_200_for_valid_form_data() { // Assert test assert_eq!(200, response.status().as_u16()); + + let saved = sqlx::query!("SELECT email, name FROM subscriptions",) + .fetch_one(&mut connection) + .await + .expect("Failed to fetch saved subscription."); + + assert_eq!(saved.email, "ursula_le_guin@gmail.com"); + assert_eq!(saved.name, "le guin"); } #[actix_rt::test]