使用factory girl

访问量: 798

refer to: http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md

factory girl的出现是为了取代rails自带的 fixtures.  后者的启动速度慢,关联关系设置的会特别麻烦。

安装: (见: http://stackoverflow.com/questions/23850979/argumenterror-factory-not-registered 要使用factory_girl_rails .

# Gemfile:   
gem 'factory_girl_rails' # 注意: 不是factory_girl, 名字要取正确。

使用:

# rails_helper: 
config.include FactoryGirl::Syntax::Methods

可以把factory (fixtures )文件定义在下面的任意地方:

test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb

下面是一个典型的例子,来自官方文档 : 

# This will guess the User class
FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    admin false
  end

  # This will use the User class (Admin would have been guessed)
  factory :admin, class: User do
    first_name "Admin"
    last_name  "User"
    admin      true
  end
end

订阅/RSS Feed

Subscribe

分类/category