Write and Run the Tests for the Models

Write the tests and initially run them to see them fail.

One of the greatest benefits of developing an application using the TDD approach is that it forces us to think and have a general sense of what we’re building. Here are the main features we aim to develop for the e-library application:

  • We’ll only have a single page that showcases all the books in the catalog. We’ll also have a form that enables users to add books to the database.
  • The fields for the Catalogue model will include the following:
    • title, which is string.
    • ISBN, which is a string.
    • author, which is a string.
    • price, which is a decimal.
    • availability, which is a string.

There are several ways of beginning an application once the project has been configured. For this project, we start from the models so we can interact with the database. After this, we move straight to the URLs for our project and application. Next, we move to the forms. Finally, we end with the template and the logic of the application, which will be the views in the case of Django.

The tests.py file

Any time we create a new Django application, we have access to a file called tests.py. This is the fastest and easiest way to write tests for our application. However, as the project grows, we can even decentralize the test file further in the following way:

  • test_models.py
  • test_forms.py
  • test_urls.py
  • test_views.py

All tests for the models will reside in the test_models.py file, while the tests for the forms will reside in the test_forms.py file, and so on.

The complete test for our models

Our model requires a database interaction for it to be tested. Therefore, we use the TestCase class instead of the SimpleTestCase class.

Here’s the complete code in continuation of the project:

Get hands-on with 1200+ tech skills courses.