2011-03-09 29 views

回答

3

Factory Girl期待您使用关联和序列,而不是硬编码的ID。以下示例为您提供了在rdoc中搜索的核心以及使用工厂的基础知识。你应该远离任何硬编码的编号,因为它会导致脆弱的测试,在某些随机场合下不起作用(这需要半天的时间才能完成)。

#the basics 
Factory.define(:post) do |f| 
    f.association :author 
end 

Factory.define(:comment) do |f| 
    f.text "boo" 
end 

# callbacks 
Factory.define :article_with_comment, :parent => :article do |article| 
    article.after_create { |a| Factory(:comment, :article => a) } 
end 

p = Factory(:article_with_comment) 
p.comments.first.text # => "boo" 
p.author #=> yep, used the association to make it 

#sequences 
Factory.define(:author) do |f| 
    f.email { Factory.next(:email) } 
end 

# and override the default behavior 
p = Factory(:post, :title => 'new post', :author => Factory(:author, :email => "[email protected]")) 
p.author.email # => [email protected] 

...deep inside a test 

p = Post.find_by_title('new post') # => this is the most basic way to get around id's 

一些更漂亮的信息在这里:http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl