2013-08-06 69 views
0

我正在調整官方Django 1.5教程中的單元測試。我試圖在ListView上測試一個空的上下文。我收到以下錯誤:Django:單元測試ListView和assertContains問題

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

,這是我的ListView代碼:

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

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

這裏是我的測試用例的方法:

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'],[]) 

但在官方教程中的民意調查等效line(https://docs.djangoproject.com/en/dev/intro/tutorial05/#testing-our-new-view):

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

我不知道哪裏「沒有民意調查」存儲在本教程提供的視圖方法的響應中,但由於某種原因它通過了 - 我的方法並沒有。

我在測試方法中丟失了什麼,所以它也通過了?

回答

1

「無投票可用」消息來自模板。從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 %} 

你需要更新你的模板rsvp_list.html包括「沒有人是可用的。」以類似的方式。

+0

感謝您的快速答覆。我很感激 :) – Paul

0

以前的答案的作品,但更有效的方式(你會不會使用冗餘的模板結構來)做的「爲空」建設這樣的:

<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>