2016-09-07 93 views
0

我已經閱讀了谷歌和我的問題的計算器並找到了一些類似的,但沒有解決我的問題。如何使用FactoryGirl和Rspec創建has_one關聯的子對象?

在我的應用程序中,用戶has_one配置文件和配置文件belongs_to用戶。

我想測試一些用戶功能,我需要創建一個測試配置文件與我的測試用戶相關聯,以便正確執行此操作。

這裏是我的工廠/ user_factory.rb

FactoryGirl.define do 

    factory :user do 

    email {Faker::Internet.safe_email} 
    password "password" 
    password_confirmation "password" 

    end 

end 

這裏是我的工廠/ profile_factory.rb

FactoryGirl.define do 

    factory :profile do 

    phone Faker::PhoneNumber.phone_number 
    college Faker::University.name 
    hometown Faker::Address.city 
    current_location Faker::Address.city 
    about "This is an about me" 
    words_to_live_by "These are words to live by" 
    first_name {Faker::Name.name} 
    last_name {Faker::Name.name} 
    gender ["male", "female"].sample 
    user 


    end 


end 

這裏是我的功能/ users_spec.rb,我需要創造我的個人資料相關聯:

require 'rails_helper' 



feature "User accounts" do 

    before do 
    visit root_path 
    end 

    let(:user) {create(:user)} 
    let(:profile) {create(:profile, user: user)} 

    scenario "create a new user" do 
    fill_in "firstName", with: "First" 
    fill_in "lastName", with: "Last" 
    fill_in "signup-email", with: "[email protected]" 
    fill_in "signup-password", with: "superpassword" 
    fill_in "signup-password-confirm", with: "superpassword" 
    #skip birthday=>fill_in "birthday", with: 
    #skip gender 
    expect{ click_button "Sign Up!"}.to change(User, :count).by(1) 


    end 

    scenario "sign in an existing user" do 




    sign_in(user) 
    expect(page).to have_content "Signed in successfully" 
    end 

    scenario "a user that is not signed in can not view anything besides the homepage" do 


    end 


end #user accounts 

在現有用戶中的場景登錄是我需要我的關聯配置文件即

現在我使用的是工廠

let(:profile) {create(:profile, user: user)} 

我試圖傳遞創建塊概要文件關聯剛剛創建一個配置文件,我嘗試了重寫的配置文件的屬性USER_ID將其與關聯創建的用戶,但都沒有工作。理想情況下,我想設置它,以便每當創建用戶時都爲其創建關聯的配置文件。有任何想法嗎?

我知道這不能太難我只是一直無法提出解決方案。謝謝您的幫助。

回答

1

最簡單的方法是建立一個與關聯名稱相同的工廠。在你的情況下,如果關聯是配置文件,並且可以隱式創建關聯的配置文件記錄以及用戶記錄。只需使用相關工廠的名稱即可。

factory :user do 
    ... 
    profile 
end 

如果您需要更多的控制,工廠女孩的協會是你所需要的。您可以覆蓋屬性並選擇與關聯名稱不同的工廠名稱。在這裏,協會名稱是教授和工廠是簡介姓氏字段被覆蓋。

factory :user do 
    ... 
    association :prof, factory: :profile, lastName: "Johnson" 
end 

您可以在Factory Girl's Getting Started找到更多的信息。

+0

我相信這解決了我的問題,但現在我得到一個堆棧級別太深的錯誤指向此行在我的user_factory:電子郵件{Faker :: Internet.safe_email}任何想法是什麼造成這種情況? – srlrs20020

+0

啊。上面的示例將該用戶配置文件創建爲工廠的一部分。我建議從配置文件工廠中刪除*用戶*行,並在用戶工廠中創建關聯。 – Fred

相關問題