Background Image
Table of Contents Table of Contents
Previous Page  212 / 478 Next Page
Information
Show Menu
Previous Page 212 / 478 Next Page
Page Background

Refactor: Transferring the new_item Functionality into view_list

Let’s take all the old tests from

NewItemTest

, the ones that are about saving POST re‐

quests to existing lists, and move them into

ListViewTest

. As we do so, we also make

them point at the base list URL, instead of

…/new_item

:

lists/tests/test_views.py (ch10l021).

class

ListViewTest

(

TestCase

):

def

test_uses_list_template

(

self

):

[

...

]

def

test_passes_correct_list_to_template

(

self

):

[

...

]

def

test_displays_only_items_for_that_list

(

self

):

[

...

]

def

test_can_save_a_POST_request_to_an_existing_list

(

self

):

other_list

=

List

.

objects

.

create

()

correct_list

=

List

.

objects

.

create

()

self

.

client

.

post

(

'/lists/

%d

/'

%

(

correct_list

.

id

,),

data

=

{

'item_text'

:

'A new item for an existing list'

}

)

self

.

assertEqual

(

Item

.

objects

.

count

(),

1

)

new_item

=

Item

.

objects

.

first

()

self

.

assertEqual

(

new_item

.

text

,

'A new item for an existing list'

)

self

.

assertEqual

(

new_item

.

list

,

correct_list

)

def

test_POST_redirects_to_list_view

(

self

):

other_list

=

List

.

objects

.

create

()

correct_list

=

List

.

objects

.

create

()

response

=

self

.

client

.

post

(

'/lists/

%d

/'

%

(

correct_list

.

id

,),

data

=

{

'item_text'

:

'A new item for an existing list'

}

)

self

.

assertRedirects

(

response

,

'/lists/

%d

/'

%

(

correct_list

.

id

,))

Note that the

NewItemTest

class disappears completely. I’ve also changed the name of

the redirect test to make it explicit that it only applies to POST requests.

That gives:

FAIL: test_POST_redirects_to_list_view (lists.tests.test_views.ListViewTest)

AssertionError: 200 != 302 : Response didn't redirect as expected: Response

code was 200 (expected 302)

[...]

FAIL: test_can_save_a_POST_request_to_an_existing_list

184

|

Chapter 10: Input Validation and Test Organisation