Skip to content

Instantly share code, notes, and snippets.

@redconfetti
Last active December 21, 2015 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redconfetti/6255612 to your computer and use it in GitHub Desktop.
Save redconfetti/6255612 to your computer and use it in GitHub Desktop.
Creating multiple associated records when using FactoryGirl
FactoryGirl.define do
factory :definition do
title "definition title"
body "definition body"
cached_slug "definition-title"
page 1
created_at "2011-01-01 08:30:00"
updated_at "2011-01-01 08:35:00"
factory :definition_object_relations_theory do
phrase { |definition| get_phrase_named("Ego") }
publication { |definition| get_publication_named("Pearl Beyond Price") }
title "Object Relations Theory"
body "Object relations theory has become the dominant psychoanalytic theory of ego development. Its main insight is that the ego develops, primarily through the integration of early experiences, into organized mental structures...."
cached_slug "object-relations-theory"
page 54
end
end
# in Cucumber or Rspec tests
@definition_1 = FactoryGirl.create(:definition_object_relations_theory)
FactoryGirl.define do
factory :phrase do
name "phrase name"
letter "a"
cached_slug "phrase-name"
created_at "2012-01-01 07:30:00"
updated_at "2012-01-01 07:35:00"
end
end
def get_phrase_named(name)
letter = name[0,1].lowercase
cached_slug = name.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
Phrase.where(:name => name).first || FactoryGirl.create(:phrase, :name => name, :letter => letter, :cached_slug => cached_slug)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment