【问题标题】:Validation error in creating factory_girl object with has_many and belongs_to association使用 has_many 和 belongs_to 关联创建 factory_girl 对象时的验证错误
【发布时间】:2014-06-12 13:36:48
【问题描述】:

我的 Rails 应用程序的 pin 模型有 belongs_to :user 而我的用户模型有_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 中创建了一个新用户,因此它给出了一个错误。我该如何克服呢?如何为同一个用户创建多个 Pin 图?

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

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    

【问题讨论】:

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


    【解决方案1】:

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

    例如。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多