lists/tests/test_views.py.
class
ListViewTest
(
TestCase
):
[
...
]
def
test_displays_item_form
(
self
):
list_
=
List
.
objects
.
create
()
response
=
self
.
client
.
get
(
'/lists/
%d
/'
%
(
list_
.
id
,))
self
.
assertIsInstance
(
response
.
context
[
'form'
],
ItemForm
)
self
.
assertContains
(
response
,
'name="text"'
)
That gives:
KeyError: 'form'
Here’s a minimal implementation:
lists/views.py (ch11l028).
def
view_list
(
request
,
list_id
):
[
...
]
form
=
ItemForm
()
return
render
(
request
,
'list.html'
, {
'list'
:
list_
,
"form"
:
form
,
"error"
:
error
})
A Helper Method for Several Short Tests
Next we want to use the form errors in the second view. We’ll split our current single
test for the invalid case (
test_validation_errors_end_up_on_lists_page
) into sev‐
eral separate ones:
lists/tests/test_views.py (ch11l030).
class
ListViewTest
(
TestCase
):
[
...
]
def
post_invalid_input
(
self
):
list_
=
List
.
objects
.
create
()
return
self
.
client
.
post
(
'/lists/
%d
/'
%
(
list_
.
id
,),
data
=
{
'text'
:
''
}
)
def
test_for_invalid_input_nothing_saved_to_db
(
self
):
self
.
post_invalid_input
()
self
.
assertEqual
(
Item
.
objects
.
count
(),
0
)
def
test_for_invalid_input_renders_list_template
(
self
):
response
=
self
.
post_invalid_input
()
self
.
assertEqual
(
response
.
status_code
,
200
)
self
.
assertTemplateUsed
(
response
,
'list.html'
)
def
test_for_invalid_input_passes_form_to_template
(
self
):
response
=
self
.
post_invalid_input
()
self
.
assertIsInstance
(
response
.
context
[
'form'
],
ItemForm
)
206
|
Chapter 11: A Simple Form