ratson / factory-bot

Fork of https://github.com/aexmachina/factory-girl
MIT License
34 stars 17 forks source link

I cannot assoc my model to another #13

Closed HromayaHorse closed 2 years ago

HromayaHorse commented 2 years ago

When I try to assoc one model to another (I copy everything from the tutorial) I get an error: (node:9444) UnhandledPromiseRejectionWarning: TypeError: model.save is not a function


factory.define('ProfileImage', ProfileImage, {
  id: factory.sequence('ProfileImage.id'),
  imageUrl: 'http://lorempixel.com/200/200'
});

factory.define('User', User, {
  email: 'user@my-domain.com',
  password: 'some-password',
  profileImage: factory.assoc('ProfileImage', 'id'),
});

factory.build('User').then(user => {
  console.log(user);
  // => User { email: 'user@my-domain.com', password: 'some-password' }
});
thiagomini commented 2 years ago

This error is throwing just by using the code presented above? If I recall correctly, this kind of error happens when your model wasn't correctly loaded with whatever ORM you are using, and thus it doesn't have the save property. To understand it better, here are some facts about this lib:

  1. Internally it uses some adapters to build and create given models. For each different ORM (like Sequelize) it has a different adapter, and calls the respective method that mimicks the expected behavior.

  2. Because of the aforementioned fact, it needs that the models you pass to the factory are already connected to the ORM AND that you use the correct adapter (Sequelize, Mongoose, Bookshelf, etc...)

So, check if your models are really defined, and if they are, if you are using the correct adapter

HromayaHorse commented 2 years ago

Ah I see. I thought I can just to associate this with the model and that's all. But If I got it correctly I should associate my model with a database and then I will be able to use assoc? Just If you follow the tutorial there isn't a mention of it. Thank you so much! I will try it out

thiagomini commented 2 years ago

Yea, it should be models connected to the database! I know the docs aren't that great to explain that haha