2015-06-29 57 views
1

試圖與工廠女孩建立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 '[email protected]' 
    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
FactoryGirl.define do 
    factory :user do 
    email '[email protected]' 
    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 
+0

不幸的是,我仍然收到'驗證失敗:用戶不能爲空' – vladra

5

一個快速的解決方法爲我的作品是包裝配置文件創建在後(:創建)塊,像這樣:

FactoryGirl.define do 
    factory :user do 
    email '[email protected]' 
    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 
0

這是建立你的個人資料和用戶的好方法廠家:

FactoryGirl.define do 
    factory :user do 
    email '[email protected]' 
    password '123456' 
    password_confirmation '123456' 

    factory :user_with_profile do 
     after(:create) do |user| 
     create(:profile, user: user) 
     end 
    end 
    end 
end 

當我們創建一個新用戶:user = build_stubbed(:user_with_profile),用戶配置文件將被創建爲好,也是如此。

如果您想了解更多關於factory girl associations的信息,本文值得一讀。