尝试与工厂女孩建立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
如果我要将用户关联添加到配置文件工厂,则会创建其他用户并将其保存到数据库。所以我有2个用户(持久和新)和1个持久用户配置文件。
我做错了什么?提前谢谢。
答案 0 :(得分: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
答案 1 :(得分:0)
FactoryGirl.define do
factory :user do
email 'user@email.com'
password '123456'
password_confirmation '123456'
trait :with_profile do
profile { Profile.create! }
end
end
factory :profile do
first_name 'First'
last_name 'Last'
type 'Consumer'
user
end
end