有人能告诉我我是否只是以错误的方式进行设置吗?
我有以下具有 has_many.through 关联的模型:
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 健全性检查:it "creates a valid listing from factory" do
Factory(:listing).should be_valid
end
这是工厂(:列表)
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
行被注释掉,那么我所有的测试都通过了。几时
association :features, :factory => :feature
错误信息是
undefined method 'each' for #<Feature>
我认为这对我有意义,因为 listing.features
返回一个数组。所以我把它改成association :features, [:factory => :feature]
我现在得到的错误是
ArgumentError: Not registered: features
以这种方式生成工厂对象是不明智的,还是我错过了什么?非常感谢您的所有意见! 最佳答案
创建这些类型的关联需要使用 FactoryGirl 的回调。
可以在此处找到一组完美的示例。
https://thoughtbot.com/blog/aint-no-calla-back-girl
把它带回家你的例子。
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
关于rspec - 如何使用 has_many 关联在 FactoryGirl 中设置工厂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6963298/