简体   繁体   中英

FactoryGirl with belongs_to / has_many association with minimum of 1 association

The issue I'm having is specific to a relationship with a belongs_to and has_many where the has_many relationship has a requirement of at least one association . This requirement is causing my Factories to fail my model level validation and not be created.

My Group model

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

The Organization model

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

Organization Factory

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

And finally the problem child: Group Factory

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

and in my test, I declare the factory instance:

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

  it "should work" do
    ...
  end
end

The errors my tests return are varied, but generally all point to FactoryGirl being unable to create an instance of the Group factory. eg

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

The method I'm using (callback) to create my Group factory is from this Thoughtbot post https://robots.thoughtbot.com/aint-no-calla-back-girl

There are many similar posts, but all of them that I've found as well as the Thoughtbot documentation don't mention this specific use case. Thanks in advance.

How about something like

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

The main idea is to build the needed objects before saving them. You may also try build_list if you need more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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