【问题标题】:Factory girl association self referencing the parent model工厂女会自参照家长模式
【发布时间】:2017-08-30 16:01:51
【问题描述】:

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

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

# 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 中做到这一点的?

谢谢。

【问题讨论】:

  • 您能否提供有关这些模型之间关联的信息? account 不仅有owner,而且还有一种has_many :users

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多