Test forms with foreign keys in Django
Testing is essential on software development because finally, it is work made by humans and we use to make mistakes. Tests can identify an error faster than a person and it is a way to prove the quality of the final product in order to ensure the customer satisfaction.
There are different ways to test forms on Django, depending on the relation between the implicated models and libraries or any other resources that can interfere by some way. It is important to know most of them to achieve testing for each functional requirement of the project in order to avoid future failures.
This tutorial was created to document how deal with the authentication Django system and testing forms that uses it. The learning curve starts testing an independent form as figure 1 shows; the difficult level of the test increase slightly testing a form with a foreign key, as in figure 2. After learned that, is easily start with the a foreign key that comes from auth_user Django table (automatic created by Django to gesture of accounts, permissions), illustrated on figure 2. Finally, the study case of this tutorial, a form with more than one foreign key that reference to auth_user table.
The most important difference between a test for an independent form and a form with one or more foreign key is the way to save the data and an extra step to create necessary objects to test that the form correctly works including the reference to objects from different models.
First, create the objects referenced by the new register and save its primary keys.
Then save the data to test on the form, passing the primary keys previously saved. This step is necessary to avoid a conflict during the creation of the objects from other models.
Finally, test it.