我在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
它失败了。这是否可以使用factorygirl调用不同的工厂并创建记录?
答案 0 :(得分:0)
因为FactoryGirl主要用于测试模型,所以我展示了 new 模型的样本模型和工厂规范。
应用/模型/ 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_user
,adv_setting
,adv_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