Testing models can be intricate, especially when reading and inserting data simultaneously during tests. This complexity arises from dynamic fields such as id or created_at, which can introduce inconsistencies into our tests.

Initializing the App

Initiate your tests with the following command:

testing::boot_test::<App, Migrator>().await;

During this initialization:

  1. Set up your application in test mode, loading the config/test.yaml file.
  2. Obtain the application context with the DB instance for interacting with the model.
  3. Perform table truncation for a clean state. documentation here
  4. Execute tests with seeded data. documentation here

Consider the example below, where we test the existence of a user in the database:

async fn can_find_by_email() {

    let boot = testing::boot_test::<App, Migrator>().await;

    let existing_user = Model::find_by_email(&boot.app_context.db, "").await;
    let non_existing_user_results =
        Model::find_by_email(&boot.app_context.db, "").await;

    assert_eq!(non_existing_user_results, false);