I'm trying to test an django ajax view that saves a field. Here's the test:
def test_ajax_save_draft(self):
self.client.force_login(self.test_user) # view requires login
sub = mommy.make(QuestSubmission, quest=self.quest2)
draft_comment = "Test draft comment"
# Send some draft data via the ajax view, which should save it.
ajax_data = {
'comment': draft_comment,
'submission_id': sub.id,
}
self.client.post(
reverse('quests:ajax_save_draft'),
data=ajax_data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
)
self.assertEqual(draft_comment, sub.draft_text) # sub.draft_text = None, as if the ajax view was never called!
And here's the view:
@login_required
def ajax_save_draft(request):
if request.is_ajax() and request.POST:
submission_comment = request.POST.get('comment')
submission_id = request.POST.get('submission_id')
sub = get_object_or_404(QuestSubmission, pk=submission_id)
sub.draft_text = submission_comment
sub.save()
response_data = {}
response_data['result'] = 'Draft saved'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
raise Http404
When I run the test, I get into the if block, and it can retrieve the comment and submission object, but when it returns to the test at the end, it's like the save never happened.
What am I doing wrong here?