The simplest would be to 

class ATestCase(TestCase):

    def setUp(self):
        super(ATestCase, self).setUp()
        self.user = UserFactory()
        self.workplace = WorkplaceFactory()
        self.workplace.employees_set.add(self.user)

    def test_foobar(self):
        # how do I add self.user to self.workplace ?
        self.assertEqual(self.workplace.employees_set.all(), 1)


Note that you probably want to use create instead of build so that the 
objects are saved to the database

 
On Tuesday, November 20, 2012 11:36:16 AM UTC-6, Craig Blaszczyk wrote:
>
> Hi Guys,
>
> I'm using FactoryBoy in my tests, but I have a model which has 
> a ManyToManyField to another model. Does anyone know if it's possible to 
> make factoryboy use a factory to represent this relationship?
>
> For reference, here are a sample model and factory:
>
> --models.py
> from django.contrib.auth.models import User
> from django.db.models import ManyToManyField
> class Workplace(models.Model):
>     employees = ManyToManyField(User)
>
> --tests.py
> import factory
> from models import Workplace
>
> # This will set the default strategy for all factories that don't define a 
> default build strategy
> factory.Factory.default_strategy = factory.BUILD_STRATEGY
>
> class WorkplaceFactory(factory.Factory):
>     FACTORY_FOR = Workplace
>
>
> class UserFactory(factory.Factory):
>     FACTORY_FOR = User
>
>
> class ATestCase(TestCase):
>
>     def setUp(self):
>         super(ATestCase, self).setUp()
>         self.user = UserFactory.build()
>         self.workplace = WorkplaceFactory.build()
>
>     def test_foobar(self):
>         # how do I add self.user to self.workplace ?
>         self.assertEqual(self.workplace.employees_set.all(), 1)
>
>
>
> --Craig
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/PO1F2ERL5CwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to