6👍
✅
Just login a user for each test. The best way to do this is to use a setUp()
method that creates a client, creates a user, and then logs user in. Also use a tearDown()
method that does the reverse (logs out user and deletes user).
The methods setUp()
and tearDown()
are run automatically for each test in the set of tests.
It would look something like this:
class Note(TestCase):
def setUp(self):
self.client = Client()
self.new_user = User.objects.create_user('blah', 'blah@blah.com', 'blah')
self.new_user.save()
self.client.login(username='blah', password='blah')
def tearDown(self):
self.client.logout()
self.new_user.delete()
def test_noteshow(self):
response = self.client.get('/note/')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, '/note/noteshow.html')
Source:stackexchange.com