Sirrah
Sirrah

Reputation: 1701

Testing page content after redirect not working

I am writing a simple unit test method which tests that a view is redirecting after receiving a POST. I can test the expected URL matches the response object but not the content.

Current shoddy code:

def test_example_view_redirects_to_home_after_post(self):
    client = Client()
    response = client.post('/example/')

    # Test location
    self.assertEqual(response.get('location'), "http://testserver/")

    # Test page content
    expected_template = render_to_string('home.html')
    self.assertEqual(response.content, expected_template)

The test is failing:

  AssertionError: b'' != '<html> etc etc...

The view code can be ultra simple at this stage:

def example(request):
    if request.method == "POST":
        return HttpResponseRedirect('/')
    else:
        return render(request, 'example.html')

I am new to TDD and just wondering why this isn't working as I might expect it to.

Thanks.

Upvotes: 1

Views: 166

Answers (1)

YPCrumble
YPCrumble

Reputation: 28682

  1. You can use follow=True in your client.post which will emulate the browser following the redirect to the next page. See here in the docs. That will allow you to test the second page's content with assertContains.

  2. You can use assertRedirects to test that the redirect happens properly. Check that out here in the docs.

Upvotes: 2

Related Questions