Zimzozaur
Zimzozaur

Reputation: 55

AssertionError in Django Unit Test: Unable to Retrieve Correct Count from Database

I'm encountering an AssertionError in my Django unit test when attempting to save a POST request to an existing list. Despite creating the list and sending the POST request successfully, the test fails with the following error:

Failure
Traceback (most recent call last):
  File "C:\ACode\TDD_Django\lists\tests.py", line 105, in test_can_save_a_POST_request_to_an_existing_list
    self.assertEqual(Item.objects.count(), 1)
AssertionError: 0 != 1

Here's the relevant code:

class NewListTest(TestCase):
    def test_can_save_a_POST_request_to_an_existing_list(self):
        # Arrange inputs and targets.
        correct_list = List.objects.create()
        # Act on the target behavior.
        self.client.post(
            f'/lists/{correct_list.id}/add_item',
            data={'item_text': 'A new item for an existing list'},
        )
        # Assert expected outcomes.
        self.assertEqual(Item.objects.count(), 1)
        new_item = Item.objects.get()
        self.assertEqual(new_item.text, 'A new item for an existing list')
        self.assertEqual(new_item.list, correct_list)

URL: path('lists/<int:list_id>/add_item/', views.add_item, name='add_item')

View:

def add_item(request, list_id):
    our_list = List.objects.get(id=list_id)
    Item.objects.create(text=request.POST['item_text'], list=our_list)
    return redirect(f'/lists/{list_id}/')

Model:

def add_item(request, list_id):
    our_list = List.objects.get(id=list_id)
    Item.objects.create(text=request.POST['item_text'], list=our_list)
    return redirect(f'/lists/{list_id}/')

I've tested the code manually using the requests library and verified that the view (add_item) works correctly. However, the unit test continues to fail. Any insights into why this test might be failing would be greatly appreciated.

Upvotes: 0

Views: 33

Answers (0)

Related Questions