[Django]-How to test Django's UpdateView?

40πŸ‘

βœ…

It seems that if you POST to a form, you have to post all required fields, not just the ones you are updating – even if the required field of the underlying model already has a value. Also, the status code returned upon a successful update is 302 β€˜Found’, not 200 β€˜OK’. So the following test passes:

class BookUpdateTest(TestCase):
    def test_update_book(self):
        book = Book.objects.create(title='The Catcher in the Rye')

        response = self.client.post(
            reverse('book-update', kwargs={'pk': book.id}), 
            {'title': 'The Catcher in the Rye', 'author': 'J.D. Salinger'})

        self.assertEqual(response.status_code, 302)

        book.refresh_from_db()
        self.assertEqual(book.author, 'J.D. Salinger')
πŸ‘€Kurt Peek

1πŸ‘

In Django 3.2, you can find here the canonical solution:
https://docs.djangoproject.com/fr/3.2/ref/urlresolvers/

In a test, you just need to:

  • create the objects with the values included in the slug,
  • and then, reverse it with these arguments:
 self.topic = Book.objects.create(slug="test-update")
        self.response = self.client.get(reverse('book_update', args=[self.topic.slug]))

0πŸ‘

TestCase has self.assertContains(response, el, html=True). html= True will render the TemplateResponse for you.

πŸ‘€alias51

Leave a comment