Can someone tell me if I'm just going about the setup the wrong way?
I have the following models that have has_many.through associations:
class Listing < ActiveRecord::Base
attr_accessible ...
has_many :listing_features
has_many :features, :through => :listing_features
validates_presence_of ...
...
end
class Feature < ActiveRecord::Base
attr_accessible ...
validates_presence_of ...
validates_uniqueness_of ...
has_many :listing_features
has_many :listings, :through => :listing_features
end
class ListingFeature < ActiveRecord::Base
attr_accessible :feature_id, :listing_id
belongs_to :feature
belongs_to :listing
end
I'm using Rails 3.1.rc4, FactoryGirl 2.0.2, factory_girl_rails 1.1.0, and rspec. Here is my basic rspec rspec sanity check for the :listing
factory:
it "creates a valid listing from factory" do
Factory(:listing).should be_valid
end
Here is Factory(:listing)
FactoryGirl.define do
factory :listing do
headline 'headline'
home_desc 'this is the home description'
association :user, :factory => :user
association :layout, :factory => :layout
association :features, :factory => :feature
end
end
The :listing_feature
and :feature
factories are similarly setup.
If the association :features
line is commented out, then all my tests pass.
When it is
association :features, :factory => :feature
the error message is
undefined method 'each' for #<Feature>
which I thought made sense to me because because listing.features
returns an array. So I changed it to
association :features, [:factory => :feature]
and the error I get now is ArgumentError: Not registered: features
Is it just not sensible to be generating factory objects this way, or what am I missing? Thanks very much for any and all input!
I tried a few different approaches and this is the one that worked most reliably for me (adapted to your case)
Alternatively, you can use a block and skip the
association
keyword. This makes it possible to build objects without saving to the database (otherwise, a has_many association will save your records to the db, even if you use thebuild
function instead ofcreate
).You could use
trait
:With
callback
, if you need DB creation:Use in your specs like this:
This will remove duplication in your factories and be more reusable.
https://robots.thoughtbot.com/remove-duplication-with-factorygirls-traits
Creating these kinds of associations requires using FactoryGirl's callbacks.
A perfect set of examples can be found here.
http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl
To bring it home to your example.
Here is how I set mine up:
And then in your tests you can do:
Hope that helps.