工厂女孩协会自我引用父模型

时间:2017-08-30 16:01:51

标签: ruby-on-rails testing rspec integration-testing factory-bot

在我的应用程序中,一个帐户可以拥有一个所有者(用户)和多个用户。

在我的测试中,我这样做:

# account_factory_static.rb
FactoryGirl.define do
  factory :account do
    name 'demoaccount'
    association :owner, :factory => :user
  end
end

# user_factory_static.rb
FactoryGirl.define do
  factory :user do
    email 'demo@example.com'
    first_name 'Jon'
    last_name 'Doe'
    password 'password'
  end
end

并使用它们如下:

let(:account) { FactoryGirl.create(:account) }

问题是,现在account.users.count等于0,因为当用户注册时,我无法像我在控制器中那样执行@account.users << @account.owner之类的操作。

问题是如何将相关帐户的ID添加到FactoryGirl中用户的account_id属性?

换句话说,你是如何在FactoryGirl中做到的?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用after :create块:

FactoryGirl.define do
  factory :account do
    name 'demoaccount'
    association :owner, :factory => :user

    after :create do |account|
      account.users << account.owner
    end
  end
end