In my model(Product) i have a validation, that each product should have a valid owner (login_id of user)
validates_presence_of :owner
validates_inclusion_of :owner, :in => User.first.login_id, :message => "%{value} is not a valid owner name"
I am trying to create product mock object using factory girl
for creating a new product I need login_id of a user. to do so i have create a user.
up to this every thing is ok, but when i am trying to create a Product using that user's login_id product is not create, and displaying validation message ("User1 is not a valid owner name").
After digging into deeper i found that
- Problem arise from validation in my model.
- I have a validation (validates_inclusion_of :owner, :in => User.first.login_id) which initialize before creating the mock user in factory.rb, (up to that time no user is created in database, user is created after initialization of model when it execute factory.rd )
My question is: 1. How do I able to create a user before initialization of model.
I solve this problem as follows:
In my model I have replaced the 'Rails validation' by writing Custom validation method. This custom validation method will be called at the time of creating 'Product'.
Can you not create a user object, and then pass that object to your product factory? This should create a valid user and then supply it through the owner association and make the product valid.
This user apparently has to be the first user too? So if you have existing user objects then you can try clearing all users before you create the first one.