factory-girl
factory-girl copied to clipboard
many factory.assoc with same parent
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:
- Is there any way I can define a "do not create a parent if it is already created" behaviour?
- 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').
Here's a solution I've used https://gist.github.com/chrisjensen/d68351424314319328967e92faee9095
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
},
}
)