Paul
Paul

Reputation: 2469

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?

Upvotes: 3

Views: 2172

Answers (2)

KhaimovMR
KhaimovMR

Reputation: 195

Previous answer works, but more effective way (you won't be using redundant template constructions) to do that with the "for-empty" construction like this:

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

Upvotes: 1

Alasdair
Alasdair

Reputation: 309089

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.

Upvotes: 2

Related Questions