问题描述
有人能告诉我我是否只是以错误的方式进行设置吗?
Can someone tell me if I'm just going about the setup the wrong way?
我有以下具有 has_many.through 关联的模型:
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
我使用的是 Rails 3.1.rc4、FactoryGirl 2.0.2、factory_girl_rails 1.1.0 和 rspec.这是我对 :listing
工厂的基本 rspec rspec 健全性检查:
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
这里是工厂(:listing)
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
:listing_feature
和 :feature
工厂的设置类似.
如果 association :features
行被注释掉,那么我的所有测试都通过了.
什么时候
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
错误信息是undefined method 'each' for #
我认为这对我来说很有意义,因为 listing.features
返回一个数组.所以我把它改成
the error message isundefined 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]
我现在得到的错误是 ArgumentError: Notregistered: features
以这种方式生成工厂对象是不明智的,还是我错过了什么?非常感谢您的所有意见!
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!
推荐答案
创建这些类型的关联需要使用 FactoryGirl 的回调.
Creating these kinds of associations requires using FactoryGirl's callbacks.
可以在此处找到一组完美的示例.
A perfect set of examples can be found here.
https://thoughtbot.com/blog/aint-no-calla-背影
把它带回家给你的例子.
To bring it home to your example.
Factory.define :listing_with_features, :parent => :listing do |listing|
listing.after_create { |l| Factory(:feature, :listing => l) }
#or some for loop to generate X features
end
这篇关于如何使用 has_many 关联在 FactoryGirl 中设置工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!