Rails + RSpec で FactoryBot(旧 FactoryGirl)を使う
FactoryBot
基本的には GETTING STARTED にしたがって導入します.
FactoryGirl が FactoryBot に変更された経緯はこちらの issue を参照してください.
Gemfile
Gemfile に factory_bot_rails
を追加して bundle install
してください.Rails の場合は factory_bot
でないことに注意してください.
gem "factory_bot_rails", "~> 4.0"
.rspec
.rspec に --require rails_helper
を追記します..rspec が存在しない場合は rails rspec:install
を実行します.プロジェクトのルートディレクトリに .rspec が生成されます.
なお,既存の .rspec に --require spec_helper
が記述されている場合はそれを削除してください.これは spec/rails_helper
が下記のように spec/spec_helper
を require するためです.
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails'
spec/rails_helper.rb
spec/rails_helper.rb
に require 'factory_bot'
を追記します.下記のように「# Add additional ...」に続けて追記するとよいでしょう.
# Add additional requires below this line. Rails is not loaded until this point! require 'factory_bot'
つづけて,RSpec.configure do |config|
以下に下記を追記します.
config.include FactoryBot::Syntax::Methods
これにより下記のように FactoryBot
シンタックスを省略できます.
# before FactoryBot.build(:user) FactoryBot.create(:user) FactoryBot.build_stubbed(:user) FactoryBot.attributes_for(:user) # after build(:user) create(:user) build_stubbed(:user) attributes_for(:user)
FactoryBot の呼び出し
導入は完了です.FactoryBot は下記に配置されたファイルを factory として自動検出します.RSpec を使用する場合は spec/factories/**/*.rb
に配置するのがよいでしょう.
test/factories.rb spec/factories.rb test/factories/*.rb spec/factories/*.rb
factory は手動で生成することもできますし,次のように rails g
を使用して自動生成することもできます.
rails g factory_bot:model User screen_name:string name:string email:string password:string
このとき,すべての factory ファイルは名前空間を共有することに注意してください.すなわち,同名の factory を別々のファイルで定義した場合,AttributeDefinitionError
が発生します.
たとえば,tasks.rb
と user.rb
で次の factory を定義した場合 AttributeDefinitionError
が発生します.
factory :admin do screen_name 'yurafuca' name "ゆらふか" email "root@yurafuca.com" password "password" password_confirmation "password" admin true end
動かない場合
FactoryBot.reload
rails_helper.rb
に下記を追記することを検討してください.
config.before(:all) do FactoryBot.reload end
この問題については下記のエントリが参考になります.
config.generators.fixture_replacement
application.rb
に下記を追加することを検討してください.
config.generators.fixture_replacement :factory_bot, dir: 'spec/factories'
この問題については下記のエントリが参考になります.
budle clean --force
下記の例外が発生する場合があります.
Unresolved specs during Gem::Specification.reset: minitest (~> 5.1)
この場合は bundle clean --force
および bundle install
を実行することを検討してください.
この問題については下記の issue が参考になります.