1
FactoryGirl.define do 

factory :agency do 
    name "Example Inc" 
    available_items "20" 
    recruiter  # recruiter.id 
end 

factory :recruiter do 
    email '[email protected]' 
    password 'please' 
    password_confirmation 'please' 
    # required if the Devise Confirmable module is used 
    # confirmed_at Time.now 
end 

end 

agency.rbFactory_girl兩款車型之間的簡單關聯

class Agency < ActiveRecord::Base 
    belongs_to :recruiter 
    validates :name, :presence => true 
end 

recruiter.rb

class Recruiter < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 
    attr_accessible :agency_attributes, :first_name 

    has_one :agency, :dependent => :destroy 

    accepts_nested_attributes_for :agency 
    validates :email, :presence => true 
end 

authentication_steps.rb

def create_user 
    @recruiter = FactoryGirl.create(:recruiter) 
end 

如何使用factory_girl複製此招聘人員&機構關聯?

+0

如果代理機構'belongs_to:招聘人員',那麼您只能爲每個代理機構申請一個招聘人員,並且您的代理機構表中有一個招聘人員ID。那是你要的嗎?我期望看到機構'has_many:招聘人員'和招聘人'belongs_to:agency'。 – 2012-04-24 17:35:43

回答

4

我想你應該從代理工廠招聘刪除,並添加機構requiter工廠

FactoryGirl.define do 

    factory :agency do 
    name "Example Inc" 
    available_items "20" 

    factory :agency_without_recuiter do 
     recuiter_id = 1 
    end 

    factory :agency_with_recuiter do 
     recuiter 
    end 
    end 

    factory :recuiter do 
    email '[email protected]' 
    password 'please' 
    password_confirmation 'please' 

    factory :recuiter_with_agency 
     agency 
    end 
    end 

end 

這應該由雙方

create(:agency).recuiter => nil 
create(:agency_with_recuiter).recuiter => recuiter 

create(:recuiter).agency => nil 
create(:recuiter_with_agency).agency => agency 

希望這將是有用的。祝你好運!

+0

如果代理機構有招聘人員,那就意味着他們有一個招聘人員ID,除非允許爲零,那麼代理機構工廠應該製作一個招聘對象,然後它可以指向它。 – MrDanA 2012-04-24 17:31:34

+0

好的我明白,但你沒有agency.recuiter_id驗證。你可以在工廠設置假recuiter_id,這樣你就可以擁有獨立的代理工廠。但我不確定這是否是一種好的做法。 – Suborx 2012-04-24 17:42:23

1

我認爲你必須在你的測試用例中複製它,而不是在FG本身。

before (:each) do 
    @recruiter = FactoryGirl.create(:recruiter) 
    @agency = FactoryGirl.create(:agency) 
    @agency.recruiter = @recruiter 
end 

這樣的事情。