Search code examples
djangodjango-1.5django-unittest

Django: issue with unit-test ListView and assertContains


I am adapting the unit tests from the official Django 1.5 tutorial. I am trying to test an empty context on a ListView. I get the following error:

AssertionError: Couldn't find 'No persons are available' in response. 

And this is my ListView code:

class RsvpListView(generic.ListView):
    template_name = 'rsvp_list.html'
    context_object_name = 'rsvplist'

    def get_queryset(self):
        return Person.objects.all()

Here is my TestCase method:

   def test_rvsp_list_view_with_no_persons(self):

        response = self.client.get(reverse('myapp:rsvp_view'))
        self.assertEqual(response.status_code,200)

        self.assertContains(response,"No persons are available.")
        self.assertQuerysetEqual(response.context['rsvplist'],[])

But in the official tutorial the Polls had the equivalent line (https://docs.djangoproject.com/en/dev/intro/tutorial05/#testing-our-new-view):

  self.assertContains(response,"No polls are available.")

I don't know where "No polls are available" is ever stored in the response from the views method that the tutorial provides but for some reason it passes - mine doesn't though.

What am I missing in my test method so it passes too?


Solution

  • The "No polls are available" message is from the template. From part 3 of the tutorial:

    {% if latest_poll_list %}
        <ul>
        {% for poll in latest_poll_list %}
            <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No polls are available.</p>
    {% endif %}
    

    You need to update your template rsvp_list.html to include "No persons are available." in a similar way.