I want to practice testing on Django and have a CreateView to test. The view allows me to create a new post and I want to check if it can find posts without a publish date, but first I want to test posts with a publish date to get used to the syntax. This is what I have:
import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Post, Comment # Create your tests here. class PostListViewTest(TestCase): def test_published_post(self): post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date' :timezone.now()}) respOnse= self.client.get(reverse('blog:post_detail')) self.assertContains(response, "really important")
But I get this:
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P\\d+)/$']
How to get the pk of this newly created post?
Thank you!
1> Daniel Rosem..:
You can get it directly from the database.
Please note that you should not call both views in your test. Each test should only call the code it actually tests, so this should be two separate views: one that calls to create the view and asserts that the entry is in the database, and one that directly creates an entry and then calls the details view to check if it show. So:
def test_published_post(self): self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone .now()}) self.assertEqual(Post.objects.last().title, "Super Important Test") def test_display_post(self): post = Post.objects.create(...whatever...) respOnse= self.client.get(reverse('blog:post_detail', pk=post.pk)) self.assertContains(response, "really important")