[英]FactoryGirl with has_many :through associations with capybara
我有以下型號:
class Productmainclass < ActiveRecord::Base
attr_accessible :name, :id, :maintext
has_many :producttaggings, :dependent => :destroy
has_many :products, :through => :producttaggings
has_many :productsubclasses
end
class Productsubclass < ActiveRecord::Base
attr_accessible :name, :id, :maintext
has_many :producttaggings, :dependent => :destroy
has_many :products, :through => :producttaggings
belongs_to :productmainclass
end
class Product < ActiveRecord::Base
attr_accessible :name, :productimage, :size, :description, :price
has_many :producttaggings, :dependent => :destroy
has_many :productsubclasses, :through => :meteoritetaggings
has_many :productmainclasses, :through => :meteoritetaggings
mount_uploader :productimage, ProductimageUploader
end
class Producttagging < ActiveRecord::Base
belongs_to :product
belongs_to :productsubclass
belongs_to :productmainclass
attr_accessible :product_id, :productsubclass_id, :productmainclass_id
end
我現在想用FactoryGirl和Capybara創建一個產品。 在規范中,我簡單地擁有:
product = FactoryGirl.create(:product)
在我的factory.rb中,我有:
factory :product do
name "Blue glass"
description "Description text of product"
productimage File.new(File.join(::Rails.root.to_s, "spec/factories/", "testimage.jpg"), 'rb')
productsubclass
productmainclass
end
factory :productsubclass do
name "Colored glasses"
productmainclass
end
factory :productmainclass do
name "Glasses"
end
運行測試,我得到:
Failure/Error: product = FactoryGirl.create(:product)
NoMethodError:
undefined method `productsubclass=' for #<Product:0xcd42090>
我認為如果您處理:product屬於productsubclass的情況,那么設置方式將可以正常工作,然后將product.productsubclass_id插入良好,就可以創建產品和productsubclass,但一切都很好,但這顯然不是您的結構,因此我們不得不使用另一種方法。 我認為@depa指出的鏈接是正確的方法,特別是本文檔中的“基本有很多關聯”部分: http ://robots.thoughtbot.com/aint-no-calla-back-girl,盡管您有has_many通過增加的復雜性。 但是從本質上講,您要先創建一個對象,然后再觸發另一個創建該對象的創建。 希望這是有道理的:)
**更新**
這是另一種方法,可能有些局限,但您可以從另一個方向創建記錄。 因此,如果您只想要每個對象/表中的一條記錄,該怎么做:
FactoryGirl.define do
factory :producttagging do
product
productsubclass
productmainclass
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.