implement test changes regarding database

also added .env for database connection details (used by sqlx)
This commit is contained in:
Nick Bland 2021-11-07 00:23:49 +10:00
parent 782796486e
commit 6db0a7bc86
No known key found for this signature in database
GPG Key ID: B46CF88E4DAB4A2C
3 changed files with 27 additions and 0 deletions

1
.env Normal file
View File

@ -0,0 +1 @@
DATABASE_URL="postgres://postgres:password@localhost:5432/newsletter"

View File

@ -22,4 +22,13 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// 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
)
}
}

View File

@ -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]