Reputation: 4558
I am new to django testing and have some issues using them to test relationship between models.
Here is an extract of my models:
class Member(models.Model):
user = models.OneToOneField('auth.User')
points = models.IntegerField()
def __unicode__(self):
return self.points
def get_number_of_poll(self):
nbr_of_poll = Poll.objects.filter(user=self.user).count()
return nbr_of_poll
class Poll(models.Model):
question = models.CharField(max_length=200)
user = models.ForeignKey(User)
def __unicode__(self):
return self.question
And here are the tests:
from polls.models import Member, Poll
from django.contrib.auth.models import User
from django.test import TestCase
class MemberTestCase(TestCase):
def setUp(self):
user = User(username='user')
self.member = Member(user=user, points=5000)
poll = Poll(question='poll', user=user)
def test_get_number_of_poll(self):
self.assertEqual(self.member.get_number_of_poll(), 1)
The issue is with the test_get_number_of_poll()
method that always returns 0. The code works as expected on the site.
Am I doing something wrong with the test? I am not sure how I am supposed to set the poll in the test class.
Upvotes: 1
Views: 1458
Reputation: 599450
You don't save any of the items you create in your setUp method. Instantiating a model object doesn't save it to the database: you should either call save()
on them, or just use User.objects.create(username='user')
etc which does the save for you.
Upvotes: 2
Reputation: 22449
The problem is that
poll = Poll(question='poll', user=user)
Only instantiates the Poll object, use the manager to actually save the object, e.g.
poll = Poll.objects.create(question='poll', user=user)
Upvotes: 1