试图与工厂女工建立一种联系却没有成功。
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个持久化用户的配置文件。
我做错什么了提前谢谢。
最佳答案
一个对我有效的快速解决方法是将概要文件创建包装在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
关于ruby-on-rails - 工厂女孩有一个协会,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31124409/