ruby-on-rails - 如何为具有 has_one/belongs_to 关系的模型创建工厂,这些关系通常被嵌套属性克服?

标签 ruby-on-rails validation factory-bot

我有一个拥有一个用户模型的帐户模型和一个属于帐户模型的用户模型。我认为演示所需的基本代码是:

class Account < ActiveRecord::Base
  has_one :user
  validates_presence_of :user
  accepts_nested_attributes_for :user
end

class User < ActiveRecord::Base
  belongs_to :account
  # validates_presence_of :account # this is not actually present,
                                   # but is implied by a not null requirement
                                   # in the database, so it only takes effect on
                                   # save or update, instead of on #valid?
end

当我在每个工厂中定义关联时:
Factory.define :user do |f|
  f.association :account
end

Factory.define :account do |f|
  f.association :user
end

我得到一个堆栈溢出,因为每个都在递归地创建一个帐户/用户。

我能够解决这个问题的方法是在我的测试中模拟嵌套的属性形式:
before :each do
  account_attributes = Factory.attributes_for :account
  account_attributes[:user_attributes] = Factory.attributes_for :user
  @account = Account.new(account_attributes)
end

但是,我想将此逻辑保留在工厂中,因为一旦我开始添加其他模块,它就会失控:
before :each do
  account_attributes = Factory.attributes_for :account
  account_attributes[:user_attributes] = Factory.attributes_for :user
  account_attributes[:user_attributes][:profile_attributes] = Factory.attributes_for :profile
  account_attributes[:payment_profile_attributes] = Factory.attributes_for :payment_profile
  account_attributes[:subscription_attributes] = Factory.attributes_for :subscription
  @account = Account.new(account_attributes)
end

请帮忙!

最佳答案

我能够通过使用 factory_girl 的 after_build 回调来解决这个问题。

Factory.define :account do |f|
  f.after_build do |account|
    account.user ||= Factory.build(:user, :account => account)
    account.payment_profile ||= Factory.build(:payment_profile, :account => account)
    account.subscription ||= Factory.build(:subscription, :account => account)
  end
end

Factory.define :user do |f|
  f.after_build do |user|
    user.account ||= Factory.build(:account, :user => user)
    user.profile ||= Factory.build(:profile, :user => user)
  end
end

这将在保存所属类之前创建关联的类,因此验证通过。

关于ruby-on-rails - 如何为具有 has_one/belongs_to 关系的模型创建工厂,这些关系通常被嵌套属性克服?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6217069/

相关文章:

java - 向模型添加验证后出现 Spring Boot 异常

php - 日期时间输入字段的值无法通过验证

php - Symfony2 验证器想成为 ValidatorInterface 的一个实例

ruby-on-rails - 如何在 rails 开发环境中使用 factory_girl 正确排序?

mysql - 如何在MySQL select语句中实现If else条件

ruby-on-rails - 如何在 EC2 上安装 sqlite3 gem?

ruby-on-rails - Rails 3 + rspec + postgres : How to run test suite against a database with foreign key constraints?

mysql - 用于编辑集合的 Rails 表单

ruby-on-rails - FactoryGirl 父类工厂随机选择其 STI 子类之一

ruby-on-rails - Factory Girl 有很多关系(和 protected 属性)