makoto's TECH

私の備忘録

【Rails】RSpecの導入

概要

RSpecとFactoryBotを使えるようにします。

メリット

テストを書いておくことによって、確実に動くことを確認しながら開発することができるため、開発効率を高めることができます。

作業

導入

RSpec

Gemfile

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails' # ここを追加
end

ターミナル

$ bundle
$ rails g rspec:install # RSpecに必要なディレクトリや設定ファイルの作成
$ rm -r ./test # Minitest用のディレクトリの削除

.rspecの編集

--require spec_helper
--format documentation # ここを追加

FactoryBot

Gemfile

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'factory_bot_rails' # ここを追加
end

ターミナル

$ bundle

spec/rails_helper.rbの編集

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods # ここを追加
end

テストでDeviseを使えるようにする

spec/support/controller_macros.rbの作成・編集

module ControllerMacros
  def login(user)
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in user
  end
end

spec/rails_helper.rbの編集

RSpec.configure do |config|
  Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }  # ここを追加
  config.include Devise::Test::ControllerHelpers, type: :controller # ここを追加
  config.include ControllerMacros, type: :controller # ここを追加
end

テストの実行

ターミナル

$ bundle exec rspec

所感

実際にどんなテストを書けば良いかは、以下の記事が参考になりました。

qiita.com