工厂女孩有一个协会

vla*_*dra 1 ruby ruby-on-rails factory-bot

试图与工厂女孩建立has_one关联但没有成功.

class User < ActiveRecord::Base
  has_one :profile
  validates :email, uniqueness: true, presence: true
end

class Profile < ActiveRecord::Base
  belongs_to :user, dependent: :destroy, required: true
end

FactoryGirl.define do
  factory :user do
    email 'user@email.com'
    password '123456'
    password_confirmation '123456'
    trait :with_profile do
      profile
    end
  end

  create :profile do
    first_name 'First'
    last_name 'Last'
    type 'Consumer'
  end
end

build :user, :with_profile
-> ActiveRecord::RecordInvalid: Validation failed: User can't be blank
Run Code Online (Sandbox Code Playgroud)

如果我将用户关联添加到配置文件工厂,则会创建其他用户并将其保存到DB.所以我有2个用户(持久和新)和1个持久用户配置文件.

我究竟做错了什么?提前致谢.

Spy*_*kis 5

对我有用的快速解决方法是将概要文件创建包装在after(:create)块中,如下所示:

FactoryGirl.define do
  factory :user do
    email 'user@email.com'
    password '123456'
    password_confirmation '123456'
    trait :with_profile do
      after(:create) do |u|
        u.profile = create(:profile, user: u)
      end
    end
  end

  factory :profile do
    first_name 'First'
    last_name 'Last'
    type 'Consumer'
  end
end
Run Code Online (Sandbox Code Playgroud)