繁体   English   中英

FactoryGirl,其belongs_to / has_many关联至少具有1个关联

[英]FactoryGirl with belongs_to / has_many association with minimum of 1 association

我遇到的问题是特定于与一个ares_many关系具有至少一个关联的要求的,与一个belongs_to和has_many的关系。 此要求导致我的工厂无法进行模型级别验证,因此无法创建。

我的群组模型

Group < ActiveRecord::Base
  has_many :organizations, dependent: nullify
  # commenting out the following line will make the tests pass
  validates :organizations, presence: true
  ...
end

组织模式

Organization < ActiveRecord::Base
  belongs_to :group
  ...
end

组织工厂

FactoryGirl.define do
  factory :organization
    name "test organization"
  end
end

最后是问题孩子:集团工厂

FactoryGirl.define do
  factory :group do
    name "test group"
    after(:create) do |group|
      create(:organization, group: group)
    end
  end
end

在测试中,我声明了工厂实例:

describe "something happens with a Group" do
  let(:group) { FactoryGirl.create :group }

  it "should work" do
    ...
  end
end

我的测试返回的错误多种多样,但通常都表明FactoryGirl无法创建Group工厂的实例。 例如

# when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank 

我使用(回调)创建我的工厂工厂的方法来自于Thoughtbot的帖子https://robots.thoughtbot.com/aint-no-calla-back-girl

有很多类似的文章,但是我发现的所有文章以及Thoughtbot文档都没有提到这个特定的用例。 提前致谢。

怎么样

FactoryGirl.define do
  factory :group do
    name 'test group'
    organizations { [association(:organization)] }
  end
end

主要思想是在保存所需对象之前先对其进行构建。 如果需要更多内容,也可以尝试使用build_list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM