Write the Actual Code

In this step, we must write the simplest code that would allow those tests to pass. The code written may not be the perfect code, but it can be refactored later. In fact, refactoring is part of the steps involved in TDD. In short, during this step, we shouldn’t aim to write the best code. Our aim should be to write the simplest code that passes when the test is rerun.

How does it work

Recall the four tests we introduced in step one. They’re just for demonstration purposes to explain the steps involved in test-driven development.

These tests are as follows:

  • test_user_profile_contains_correct_html
  • test_user_profile_template
  • test_user_profile_code
  • test_create_user_profile.

Sample one

Let’s write the simplest code that would make the test_user_profile_contains_correct_html test function pass. For this, we only need to include the word Profile in the HTML file when we navigate to the route mapped to the URL name user:

...
<body>
    <h3>Profile</h3>
</body
...

Sample two

Then, we write the simplest code for the test_user_profile_template test to run successfully. This test checks if the template used is correct when we navigate to the route mapped to the URL name user. Therefore, we just need to update both the urls.py and views.py files in the following ways.

The urls.py file

Update the urls.py file as follows:

...
urlpatterns = [
    path('/user', views.user, name='user')
]

The views.py file

Update the views.py file as follows:

def user(request):
    return render(request, 'user.html')

Sample three

Next, we write the simplest code for the test_user_profile_code test to run successfully. This test ensures that the URL mapped to the URL name user exists. If it does, it should return a status code of 200, which stands for success. Therefore, we only need to update the urls.py file that was shown earlier.

The urls.py file

Update the urls.py file as follows:

...
urlpatterns = [
    path('/user', views.user, name='user')
]

Sample four

Now, we write the simplest code for the test_create_user_profile test to run successfully. For this test to run successfully, we need to create the model.

The models.py model

Create the model in the following way:

from django.db import models

class Profile(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

    def __str__(self):
        return self.first_name

The four sample code snippets show what we need to implement to esnure our tests run successfully.

Get hands-on with 1200+ tech skills courses.