如何创建与 FactoryGirl 和 Rspec 关联的 has_one 子对象?

How to create a child object of a has_one association with FactoryGirl and Rspec?

我浏览了 google 和 Whosebug 并找到了一些类似的问题,但 none 解决了我的问题。

在我的应用程序中,一个用户 has_one 个人资料和一个个人资料 belongs_to 用户。

我正在尝试测试一些用户功能,我需要创建一个与我的测试用户关联的测试配置文件才能正确执行此操作。

这是我的 factories/user_factory.rb

FactoryGirl.define do 

  factory :user do 

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

  end

end

这是我的 factories/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

这是我的 features/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@email.com"
    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 属性以将其与创建的用户关联,但都没有用。理想情况下,我想对其进行设置,以便无论何时创建用户,都会为其创建关联的配置文件。有什么想法吗?

我知道这不会太难,但我还没有想出解决方案。感谢您的帮助。

最简单的方法就是拥有一个与协会同名的工厂。在您的情况下,如果关联是 profile,您可以隐式创建关联的配置文件记录以及用户记录。就用关联工厂的名字,像这样。

factory :user do
   ...
  profile
end

如果您需要更多的控制权,工厂女郎的协会就是您所需要的。您可以覆盖属性和 select 与关联名称不同的工厂名称。这里,协会名称是 prof,工厂是 profilelastName 字段被覆盖。

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

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