我正在调整官方Django 1.5教程中的单元测试。我试图在ListView上测试一个空的上下文。我收到以下错误:
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()
这是我的TestCase方法:
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'],[])
但在官方教程中,民意调查的等效线(https://docs.djangoproject.com/en/dev/intro/tutorial05/#testing-our-new-view):
self.assertContains(response,"No polls are available.")
我不知道“没有可用的民意调查”的地方存储在教程提供的视图方法的响应中,但由于某种原因它通过了 - 但我的不是。
我的测试方法中缺少什么,所以它也通过了?
答案 0 :(得分: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以包含“没有人可用”。以类似的方式。
答案 1 :(得分:0)
以前的答案有效,但更有效的方式(您不会使用冗余模板构造)来使用&#34; for-empty&#34;像这样的建筑:
<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>