Skip to content

Commit

Permalink
modified tests to check db entry and get config settings
Browse files Browse the repository at this point in the history
  • Loading branch information
nathannli committed Apr 21, 2024
1 parent 41530d9 commit 46ae208
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use sqlx::{Connection, PgConnection};
use std::net::TcpListener;
use zero2prod::configuration::get_configuration;

#[tokio::test]
async fn health_check_works() {
Expand All @@ -19,19 +21,27 @@ fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port");
// get random port
let port = listener.local_addr().unwrap().port();
let server = zero2prod::run(listener).expect("Failed to bind address");
let server = zero2prod::startup::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
// return the application address and the port number
format!("http://127.0.0.1:{}", port)
}

#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
// setup
// get web app url
let app_address = spawn_app();
// get web app & db config
let configuration = get_configuration().expect("failed to get config");
// setup postgres connection
let connection_string = configuration.database.connection_string();
let mut connection = PgConnection::connect(&connection_string)
.await
.expect("failed to connect to postgres");
// create web app endpoint
let client = reqwest::Client::new();

// test
// test web app received post request
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
let response = client
.post(&format!("{}/subscriptions", &app_address))
Expand All @@ -43,6 +53,15 @@ async fn subscribe_returns_a_200_for_valid_form_data() {

// assert test gets ok
assert_eq!(200, response.status().as_u16());

// test db has written test entry
let saved = sqlx::query!("select email, name from subscriptions",)
.fetch_one(&mut connection)
.await
.expect("fail to fetch test entry");

assert_eq!(saved.email, "[email protected]");
assert_eq!(saved.name, "le guin");
}

#[tokio::test]
Expand Down

0 comments on commit 46ae208

Please sign in to comment.