2013-12-23 48 views
-1

我在我的rails應用程序中使用FactoryGirl。我有以下代碼片段如何在其他文件中調用工廠方法

FactoryGirl.define do 
    factory :pub_company, :class => Company do |c| 
    c.name "Dixons Group" 
    c.address "1500 Martin Ave" 
    c.city "Santa Clara" 
    c.state "CA" 
    end 
end 

FactoryGirl.buid(:pub_company) 

上面的代碼可以創建記錄罰款。我正在嘗試創建更多類似於以上的數據。所以,我正在使用

require 'factory_girl_rails' 
FactoryGirl.define do 
    factory :new do 
    FactoryGirl.create(:pub_company) 
    FactoryGirl.create(:adv_user) 
    FactoryGirl.create(:adv_setting) 
    FactoryGirl.create(:adv_ad) 
    end 
end 

它失敗了。這可能使用工廠女孩來調用不同的工廠並創建一個記錄?

+0

是'這裏build'一個錯字:'FactoryGirl.buid(:pub_company)'? – vee

+0

home/gems/factory_girl-4.3.0/lib/factory_girl/registry.rb:24:在find中:Factory not registered:pub_company(ArgumentError)另外,FactoryGirl.build試着得到相同的錯誤。 – Pez

+0

你爲什麼在這裏'factory_girl_r ails'的空間? –

回答

0

因爲FactoryGirl主要用於測試模型,所以我展示了新型號型號的示例型號和工廠規格。

應用程序/模型/ new.rb

class New < ActiveRecord::Base 
    attr_protected :company_id 
    belongs_to :company 
end 

應用程序/模型/ company.rb

class Company < ActiveRecord::Base 
    attr_accessible :name, :address, :city, :state 
    has_many :news 
end 

規格/工廠/ company_factory.rb

FactoryGirl.define do 
    factory :company do |c| 
    c.name "Dixons Group" 
    c.address "1500 Martin Ave" 
    c.city "Santa Clara" 
    c.state "CA" 
    end 
end 

規格/工廠/ new_factory.rb

FactoryGirl.define do 
    factory :new do 
    company { FactoryGirl.create :company } 
    # adv_user { FactoryGirl.create :adv_user } 
    # adv_setting { FactoryGirl.create :adv_setting } 
    # adv_ad { FactoryGirl.create :adv_ad } 
    end 
end 

注意:您外殼有adv_useradv_settingadv_ad還定義。

規格/型號/ new_spec.rb

describe New do 
    it 'Test new model' do 
    new_instance = FactoryGirl.create :new 
    new_instance.pub_company.name.should == "Dixons Group" 
    ... 
    end 
end 
+0

當以上時,它劑量創建任何記錄。它可以產生沒有發現的例子。 在0.00007秒內完成 0個例子,0個故障 – Pez

+0

@Pez這意味着你還沒有在rspec/cucumber中定義一個測試樣本...創建一個測試,shell使用Factory。 –

+0

所有文件都在規範/工廠 – Pez

相關問題