Skip to content

Instantly share code, notes, and snippets.

@stevenringo
Created July 12, 2011 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevenringo/1077311 to your computer and use it in GitHub Desktop.
Save stevenringo/1077311 to your computer and use it in GitHub Desktop.
Has Many through factory with fabricator
class Country < ActiveRecord::Base
has_many :registrations
has_many :members
has_many :distribution_groups, :through => :members
end
class DistributionGroup < ActiveRecord::Base
has_many :members
has_many :countries, :through => :members
end
class Member < ActiveRecord::Base
belongs_to :country
belongs_to :distribution_group
end
Fabricator(:country) do
name { Faker::Address.country }
end
Fabricator(:member) do
end
Fabricator(:distribution_group) do
name { Faker::Lorem.words(3).join(" ") }
after_build do |distribution_group|
2.times { Fabricate(:member, :distribution_group => distribution_group, :country => Fabricate(:country)) }
end
end
@paulelliott
Copy link

If a Member has to have a country, then you can declare that in the Fabricator and it will generate one automatically and associate it. You can still override it at Fabricate time by passing one in explicitly, but in that case you wouldn't have to.

Fabricator(:member) do
  country
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment