That's all, and now we have a crate that can be used to interact with a database. Since it's not binary, we need to guarantee that the code works correctly. It's a good practice to cover your code with tests, and we will do that now.
Add the following code to the lib.rs file:
#[cfg(test)]
mod tests {
use super::Api;
#[test]
fn create_users() {
let api = Api::connect().unwrap();
let user_1 = api.register_user("[email protected]").unwrap();
let user_2 = api.register_user("[email protected]").unwrap();
let channel = api.create_channel(user_1.id, "My Channel", false).unwrap();
api.publish_channel(channel.id).unwrap();
api.add_member(channel.id, user_2.id).unwrap();
let message = api.add_message(channel.id, user_1.id, "Welcome!").unwrap();
api.add_message(channel.id, user_2.id, "Hi!").unwrap();
api.delete_message(message.id).unwrap();
}
}
We added a test module and a create_users testing function. This function tests all the API methods we implemented. It creates an Api instance with a connect method call and uses that instance to register two users with the following emails—"[email protected]" and "[email protected]". After that, it creates a channel for the first user, publishes it, and add the second user as a member. At the end, it adds two messages and deletes the first one. Let's run this test, but you have to run a PostgreSQL database instance with Docker. You can read how to do this in the previous chapter.
Apply all the migrations and run the test:
DATABASE_URL=postgres://postgres@localhost:5432 diesel migration run && cargo test
When the testing is over, you will get a message with from the psql client:
postgres=# select * from messages;
id | timestamp | channel_id | user_id | text
----+----------------------------+------------+---------+------
2 | 2019-01-08 18:30:48.465001 | 1 | 2 | Hi!
(1 row)
As you can see, the test added two records and removed the first. In Chapter 13, Testing and Debugging Rust Microservices, we will discuss testing microservices in detail.