请问我是否设置方式不正确?
我有以下模型,它们具有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。这是我的基本rspec健全性检查,关于:listing
工厂:
it "creates a valid listing from factory" do
Factory(:listing).should be_valid
end
这里是 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
这一行,则所有测试都会通过。
当它被取消注释时,
association :features, :factory => :feature
错误消息是
undefined method 'each' for #<Feature>
,我认为这很有道理,因为listing.features
返回的是数组。所以我将其更改为
association :features, [:factory => :feature]
现在我得到的错误是ArgumentError: Not registered: features
,只是用这种方式生成工厂对象不明智吗?或者我漏掉了什么?非常感谢您所有的帮助!
association
关键字使用相同的构建策略来构建父对象和子对象。因此,它可以构建对象而无需保存到数据库中。 - Nick