LoginSignup
48
30

More than 3 years have passed since last update.

RailsでRSpecの初期設定を行う際のテンプレートを作ってみる

Last updated at Posted at 2018-08-06

はじめに

RailsでRSpecを導入する際に、毎回初期設定を忘れがちになるので、テンプレートとしてまとめてみます。

また、この記事はこの記事はTwitterで人気のハッシュタグ#100DaysOfCodeをつけて、
100日間プログラミング学習を続けるチャレンジに挑戦した46日目の記録です。

.rspec

# 出力結果を色分け
--color
# rails_helperの読み込み
--require rails_helper
# 出力結果をドキュメント風に見やすくする
--format documentation

rails generate rspec:installを実行すると作成されるファイル。

デフォルトだと--require spec_helperとなっているが、RailsでRSpecを使う場合は、--require rails_helperを使うのがベター。

理由としては、後述するrails_helper.rbで既にrequire spec_helperを行なっているため。

混乱しそうなのでまとめると、次の通り。

.rspecの設定 シュチュエーション
--require rails_helper RailsでRSpecを使う時
--require spec_helper Ruby単体で使用するとき

config/application.rb

config.generators do |generator|
  generator.test_framework :rspec,
                   fixtures: true,
           controller_specs: true,
               helper_specs: false,
              routing_specs: false
  generator.fixture_replacement :factory_bot, dir: "spec/factories"
end

ここで設定しているのは、generatorを使う際に生成されるファイルたち。

テストフレームワークにrspecを指定することで、rails g ~を実行した際、自動的にspecファイルも作成してくれるというもの。

この辺はプロジェクトや開発者によって設定方法が異なるので、それぞれに合わせるのがいいかと。

spec/rails_helper

# 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__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'factory_bot'
require 'faker'
 Dir[Rails.root.join("spec/support/**/*.rb")].each { |file| require file}
 begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
 RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")
  config.inculde FactoryBot::Syntax::Methods
end

RSpec用の設定ファイルの一つ。

このファイルではRails固有のspec設定を行う際にいじるものですね。

基本的にはRSpecのドキュメント通りに設定しておけば問題ない。

spec/spec_helper

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
   config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
   config.shared_context_metadata_behavior = :apply_to_host_groups
end

rails_helper.rbと同様に、RSpec用の設定ファイル。

こちらも、基本的にはRSpecのドキュメント通りに設定しておけば問題ないですね。

まとめ

spec/rails_helper.rbspec/spec_helper.rbはプロジェクトや人によって設定が違うから多種多様で面白いですねー。

細かい設定ファイルとかあるので、色々と調べてみると面白いかもしれません。

48
30
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48
30