我已经阅读了谷歌和我的问题的计算器并找到了一些类似的,但没有解决我的问题。如何使用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将其与关联创建的用户,但都没有工作。理想情况下,我想设置它,以便每当创建用户时都为其创建关联的配置文件。有任何想法吗?
我知道这不能太难我只是一直无法提出解决方案。谢谢您的帮助。
我相信这解决了我的问题,但现在我得到一个堆栈级别太深的错误指向此行在我的user_factory:电子邮件{Faker :: Internet.safe_email}任何想法是什么造成这种情况? – srlrs20020
啊。上面的示例将该用户配置文件创建为工厂的一部分。我建议从配置文件工厂中删除*用户*行,并在用户工厂中创建关联。 – Fred