2011-01-23 70 views
2

我有以下型號:factory_girl的黃瓜步驟和可選協會

class Person < ActiveRecord::Base 
    belongs_to :family 
end 

class Family < ActiveRecord::Base 
end 

而下面的工廠:

Factory.define :person do |p| 
    p.association :family 
end 

Factory.define :family do |f| 
end 

而且我使用factory_girl的黃瓜步驟是這樣的:

Given the following people exist: 
    | First name | Last name | 
    | John  | Doe  | 

Given the following people exist: 
    | First name | Last name | Family    | 
    | John  | Doe  | Name: Doe's family | 

我想使用第一種形式創建沒有關聯的家庭的人,而後者創建人與家人一起。現在每個人都有一個家庭。實際上,使用第一種形式失敗,因爲我也有類validates_presence_of :name

如果我從Person工廠定義中刪除p.association :family,後者的方式失敗,因爲它試圖爲相關記錄(它運行像family = "Name: ...")設置字符串。

是否可以在factory_girl定義的Cucumber步驟中具有可選關聯?

回答

3

我創建了另一家工廠,如:

Factory.define :orphan, :class => "Person" do |factory| 
    # does not belong to a family 
end 

然後使用您的第一個設置:

Given the following orphans exist: 
    | First name | Last name | 
    | John  | Doe  | 
1

我會想辦法讓你的缺省人SANS關聯,然後定義一個孩子廠這增加了關聯性,這可能有點違反直覺,但是是建立類層次結構的正確方式:

Factory.define(:person) do |f| 

end 

Factory.define(:family_member, :parent => :person) do |f| 
    f.association(:family) 
end