使用has_many和belongs_to关联创建factory_girl对象时的验证错误

时间:2014-06-12 13:36:49

标签: ruby-on-rails associations factory-bot

我的Rails应用程序的pin模型有belongs_to:user,而我的用户模型has_many:pins。我的应用程序不允许多个注册的电子邮件。我想为单个用户创建多个引脚。在下面的黄瓜步骤中,我创建了2个具有相同描述但具有不同图像的引脚。一个具有默认图像,而另一个具有上载的不同图像。 以下是我的黄瓜步骤 -

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

它给出了一个验证错误,指出电子邮件已经注册。

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

似乎在@ pin2中正在创建一个新用户,因此它会出错。我怎么能克服这个?如何为同一用户创建多个引脚?

以下是我的工厂定义方法 -

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  "blah@p.com"
  password "test1234"
  password_confirmation "test1234"
 end
end    

1 个答案:

答案 0 :(得分:2)

这很简单 - 当你创建第二个引脚时,指定应该为哪个用户创建引脚。

例如

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