Reputation: 1295
def test_saving_a_POST_request(self):
request = HttpRequest()
request.method = "POST"
request.POST['item_text'] = "A new list item"
response = new_list(request)
# response = self.client.post('lists/new', {'item_text': "A new list item"})
new_item = Item.objects.first()
self.assertEqual(Item.objects.count(), 1)
self.assertEqual(new_item.text, 'A new list item')
This is the method used to test post response of the new_list view. It works fine when i use HttpRequest(), it throws error when i tried to use inbuilt client to post(the commented line) the data rather than HttpRequest.
The error:
======================================================================
FAIL: test_saving_a_POST_request (lists.tests.NewListTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/prabhath/PycharmProjects/superlists/lists/tests.py", line 95, in test_saving_a_POST_request
self.assertEqual(Item.objects.count(), 1)
AssertionError: 0 != 1
----------------------------------------------------------------------
I think there is a problem with how i use the client to post data. This is the link for the section in textbook that i was reading. Any help is appreciated.
Django -- 1.9.5, python -- 3.5
Upvotes: 0
Views: 137
Reputation: 5819
I would guess that your view's URL is not being referenced correctly. You most likely want to use Django's built-in URL resolution methods instead of hard coding the url, lists/new
, like you have. This would make your test case look something like this:
from django.core.urlresolvers import reverse_lazy
from django.test import TestCase
from .models import Item
class ItemTestCase(TestCase):
def test_saving_a_POST_request(self):
response = self.client.post(reverse_lazy('new_list'), {'item_text': "A new list item"})
new_item = Item.objects.first()
self.assertEqual(Item.objects.count(), 1)
self.assertEqual(new_item.text, 'A new list item')
Upvotes: 3