N
N
Nikita Pewget2014-05-30 21:37:24
Django
Nikita Pewget, 2014-05-30 21:37:24

How to check for changes in db when testing django view?

Hello!
I'm trying to write a test for django view.
There are some model changes being made in the view and I would like to check if they happened in the end.
For example:

# models.py
class Post(models.Model):
    title = models.CharField(max_length=255)

# view.py
def index(request):
    post = Post.objects.get(pk=1)
    post.title = "Second post"
    post.save()
    return HttpResponse(post.title)

I'm writing a test that creates a post with the title "Hello World". Because in the view title of the post changes to "Second post", it would be logical to assume that we will eventually get this value in the test as well.
# tests.py
class BlogTest(TestCase):
    def test_post(self):
        post = Post.objects.create(title="Hello World")
        print "Title before request:", post.title
        resp = self.client.get('/')
        print "From view:", resp.content
        print "Title after request:", post.title

However, all model changes inside the view are not saved, and after the request is completed, we get the same title value that was before the request was called, despite all the changes inside the called view:
➜  djangotests  ./manage.py test
Creating test database for alias 'default'...
Title before request: Hello World
From view: Second post
Title after request: Hello World

You can download the code here: https://www.dropbox.com/s/k149ud6cmhfx1qh/djangote...
I suspect that this behavior is correct and I just misunderstand something in the concept of unit tests, but how then to achieve this behavior which I require?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question