0

I have two classes PublisherLevel and Publisher. If we create a publisher, the PublisherLevel count should be equal to 14 - the count of different publisher level types. In our db, we have a foreign key constraint. This is just a lookup table. I'd like to do someithing like this:

FactoryGirl.define do
  if PublisherLevel.count == 0 
    puts "you have 0 publisher_levels and should seed it"
    seed_publisher_levels
  end
  factory :company do
    name { Faker::Company.name }
    display_name "Sample Company"
    publisher_level 
  end
end

but the first if statement doesn't get called. I have seen this Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors but is 8 years old and suspect there is a more elegant solution. What is the canonical way to do this?

timpone
  • 19,235
  • 36
  • 121
  • 211

1 Answers1

1

It seems that you want seed data. You can create your own seeds class to cache the necessary data:

class Seeds
  def [](name)
    all.fetch(name)
  end

  def register(name, object)
    all[name.to_sym] = object
  end

  def setup
    register :publisher_level_1, FactoryGirl.create(:publisher_level, :some_trait)
    register :publisher_level_2, FactoryGirl.create(:publisher_level, :some_other_trait)
  end

  private

  def all
    @all ||= {}
  end
end

And then in your test_helper.rb, call:

require 'path/to/seeds.rb'
Seeds.setup

Finally, refer it in your factories:

factory :company do
  publisher_level { Seeds[:publisher_level_1] }
end

This code is just an example of the usage, you will have to tweak it to make it behave according to your needs.

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117