Manmeet
Manmeet

Reputation: 27

Validation error in creating factory_girl object with has_many and belongs_to association

The pin model of my Rails application has belongs_to :user while my user model has_many :pins. My application does not allow more than one registered email. I want to create multiple pins for a single user. In the cucumber step below I create 2 pins with the same description but with different images. One has the default image while the other has a different image uploaded. The following is my cucumber step -

When(/^I click on pin $/) do
 @pin = create(:pin)
 @pin2 = create(:pin, :image => fixture_file_upload("blah_pic2.jpg",'image/jpg'))
 visit root_path
end

It gives me a validation error stating that Email is already registered.

Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

Seems like in @pin2 a fresh user is being created and hence it gives an error. How can I overcome this? How can I create multiple pins for the same user?

The following is my factory definition method -

FactoryGirl.define do
 factory :pin do |p1|
  # Given a pin model with has_attached_file :image
  p1.image {fixture_file_upload("#{Rails.root}/public/images/blah_pic.jpg",'image/jpg')}
  p1.description "that's me"
  user
end

factory :user do
  name "John Dover"
  email  "[email protected]"
  password "test1234"
  password_confirmation "test1234"
 end
end    

Upvotes: 0

Views: 80

Answers (1)

sevenseacat
sevenseacat

Reputation: 25049

It's simple - when you create the second pin, specify which user the pin should be created for.

eg.

@pin2 = create(:pin, :user => @pin.user, :image => fixture_file_upload("blah_pic2.jpg",'image/jpg'))

Upvotes: 2

Related Questions