factory-girl icon indicating copy to clipboard operation
factory-girl copied to clipboard

many factory.assoc with same parent

Open brunosiqueira opened this issue 7 years ago • 2 comments

Helly Simon. Congrats on the lib. I've been using it since 2016. Today I migrated to the 4.3.0 version as I am creating new tests in my application. Right now I have the following models:

factory.define('testUser2', db.user, {
  username: 'testuser2',
  name: 'Test User 2',
  email: '[email protected]',
  role: 'admin_3',
  isAdmin: true,
  passwordHash: passwordHash,
  passwordSalt: passwordSalt
});
//incident
factory.define('incident', db.incident, {
  date: moment().subtract(35, 'day').toISOString(),
  lat: -23,
  lng: 43,
  userId: factory.assoc('testUser2', 'id')
});

//videos
factory.define('videoNoIncident', db.video, {
  date: moment().subtract(36, 'day').toISOString(),
  uploaderId: factory.assoc('testUser2', 'id'),
  userId: factory.assoc('testUser2', 'id'),
  duration: 300,
  filesize: 154233
});
factory.define('videoWithIncident', db.video, {
  date: moment().subtract(36, 'day').toISOString(),
  uploaderId: factory.assoc('testUser2', 'id'),
  userId: factory.assoc('testUser2', 'id'),
  duration: 300,
  filesize: 154233,
  hasIncident: true
});
factory.define('videoIncidentSameTime', db.video, {
  date: moment().subtract(35, 'day').toISOString(),
  uploaderId: factory.assoc('testUser2', 'id'),
  userId: factory.assoc('testUser2', 'id'),
  duration: 300,
  filesize: 154233
});

In my test, I try to create all the models but, since they all are associated with testUser2, then it gets an error for unique fields (since it tries to recreate it 4 times).

So my questions are:

  1. Is there any way I can define a "do not create a parent if it is already created" behaviour?
  2. If I remove the factory.assoc('testUser2', 'id') from all the children and try to set a factory.assocMany in the parent, how can I define the different models I want to create? eg: factory.assoc('videoIncidentSameTime', 'videoWithIncident', 'videoNoIncident').

brunosiqueira avatar Jan 05 '18 14:01 brunosiqueira

Here's a solution I've used https://gist.github.com/chrisjensen/d68351424314319328967e92faee9095

chrisjensen avatar Jan 06 '18 13:01 chrisjensen

My solution:

  factory.define(
    'FtpUser',
    models.FtpUser,
    {
      accountId: factory.assoc('Account', 'id'),
    },
    {
      afterBuild: async model => {
        const account = await models.Account.query().findById(model.accountId)

        if (!model.name) {
          model.name = account.email
        }

        return model
      },
    }
  )

oliviertassinari avatar May 09 '18 13:05 oliviertassinari