可能是一件简单的事情,但是我的一个测试失败了,这让我很烦恼。
我有一个视图,它处理来自表单的POST请求以编辑模型。我不明白为什么这个测试失败了(名字没有改变):
def test_edit_club_view(self):
"""
Test changes can be made to an existing club through a post request to the edit_club view.
"""
new_club = Club.objects.create(
name = "new club name unique"
)
self.client.post("/clubs/edit/{}/".format(new_club.pk), data = {"name": "edited_club_name"})
self.assertEqual(new_club.name, "edited_club_name")
表单测试通过:
def test_club_can_be_changed_through_form(self):
"""
Test the ClubForm can make changes to an existing club in the database.
"""
form_data = {
"name": "new club name"
}
add_club_form = ClubForm(data = form_data, instance = self.existing_club)
add_club_form.save()
self.assertEqual(self.existing_club.name, "new club name")
此外,如果我在视图中打印name
字段的值,它似乎会在那里更改,但不会反映在测试用例中。
AssertionError: 'new club name unique' != 'edited_club_name'
答案 0 :(得分:6)
您需要在帖子后从数据库重新加载new_club
。
new_club.refresh_from_db()