Ruby on rails FactoryGirl属于/有多个协会,至少有一个协会

Ruby on rails FactoryGirl属于/有多个协会,至少有一个协会,ruby-on-rails,rspec,Ruby On Rails,Rspec,我遇到的问题是特定于与a所属和has-many的关系,其中has-many关系要求至少有一个关联。这一要求导致我的工厂无法通过模型级验证,无法创建 我的团队模型 Group < ActiveRecord::Base has_many :organizations, dependent: nullify # commenting out the following line will make the tests pass validates :organizations, pr

我遇到的问题是特定于与a所属和has-many的关系,其中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
最后是问题儿童: 集团工厂

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无法创建
组的实例。e、 g

# when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank 
我使用(回调)创建我的组工厂的方法来自这篇Thoughtbot文章


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

像这样的东西怎么样

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

其主要思想是在保存所需对象之前构建它们。如果您需要更多信息,也可以尝试
build\u list

Ahh!成功了!哇,我厌倦了这个主题的很多变化,但我的语法是错误的。太棒了,谢谢!
# when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank 
FactoryGirl.define do
  factory :group do
    name 'test group'
    organizations { [association(:organization)] }
  end
end