Factory Girl and has_many :through
If you are using Factory Girl, then you may be wondering how to define the factories for those has_many :through associations you have.
Models
The example models we will use are:
class BeeKeeper < ActiveRecord::Base
has_many :bees
has_many :hives, :through => :bees
end
class Hive < ActiveRecord::Base
has_many :bees
has_many :bee_keepers, :through => :bees
end
class Bee < ActiveRecord::Base
belongs_to :bee_keeper
belongs_to :hive
end
Factories for Testing
So, to test these relationships you would define Factories. Let's start by specifying the belongs_tos
Factory.define :bee do |b|
b.bee_keeper {|a| a.association(:bee_keeper)}
b.hive {|a| a.association(:hive)}
end
Factory.define :bee_keeper do |bk|
end
Factory.define :hive do |h|
end
By creating a bee, it should also create a beekeeper and a hive.
We're Done!
Actually, this is all you need to do for has_many :through - when you add hives to bee_keepers, they will automatically create the bees!
context "Bee Keepers" do
setup do
@bee_keeper = Factory(:bee_keeper)
@bee_keeper.hives << Factory(:hive)
@bee_keeper.hives << Factory(:hive)
end
should "have 2 hives" do
assert_equal 2, @bee_keeper.hives.length
end
should "have 2 bees" do
assert_equal 2, @bee_keeper.bees.length
end
end
This will create:
- 1 bee keeper
- 2 bees
- 2 hives
Hope this helps some of you.
mod_rails on Dreamhost
I have just turned on mod_rails on Dreamhost. Let's see how it goes.
Where to Find Me
My lack of posting here is because I have been spending time elsewhere. You can find me at the following hang outs:
- Twitter - I tweet pretty much every day.
- Flickr - I post photos here at least once a week, usually more.
- Upcoming - You can see what I'm up to or interested in going to.
- Google Reader Shared - funny or interesting stuff I find in my RSS feeds.
- Delicious - Any links which don't come from RSS feeds.
- Github - It's where the cool kids keep their code these days.
- Lighthouse - Issue tracking, seeing use now because they now accommodate open source projects for free.
- Dopplr - Where am I?
- LinkedIn - Only vaguely using this. Just barely more useful than Facebook.
- Facebook - I removed my account over a year ago, due to the pointlessness of it. Don't try to contact me there.
Pollen London
Hayfever is back with our first stint of summer weather.
In order to give us some warning, I have created a twitter bot which tweets daily based on information found at the BBC website. It currently reports on London only.
- pollen_london - Twitter account
- Github - Source code is open source
- Lighthouse - Please report bugs









