21
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rspecの設定はrails_helper.rbにだけ書けばよい

Posted at

今までRspecを使うときは、漫然と先人のコードをコピペして、設定をrails_helper.rbに書いたりspec_helper.rbに書いたりしていましたが、「rails_helper.rbにだけ書けばよい」という結論に至りました。

次のStack Overflowの回答を参照。spec_helper.rbは、Railsを読み込まずにRspecだけで何かしらRubyのコードをテストするのに使うらしい。

ruby on rails - How is spec/rails_helper.rb different from spec/spec_helper.rb? Do I need it? - Stack Overflow

Rspecが生成するrails_helper.rbのテンプレートの先頭は次のようになってます。まず、spec_helper.rbを読み込み、その後でRails(config/environment)を読み込みます。

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'

テストスクリプトの先頭でrails_helper.rbを読み込めば、RailsとRspecが使えます。

require 'rails_helper'

代わりにspec_helper.rbを読み込めば、RailsなしでRspecが使えます。

require 'spec_helper'

といっても、普通のRailsアプリケーションで、Railsを使わずにテストをする、というケースは考えにくい。なら、rails_helper.rbにだけ設定をまとめたほうが分かりやすくていいんじゃないでしょうか(spec_helper.rbのほうは自動生成されたものを放置すればいい)。

今いじっているプロジェクトのrails_helper.rbは次のような感じにしました(長いコメントは除く)。

rails_helper.rb
# simplecovは最初に
require 'simplecov'
SimpleCov.start 'rails'

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'

# spec/supportの下読み込み
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

# Capybara設定
Capybara.server = :puma, { Silent: true }

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end

RSpec.configure do |config|
  # FactoryBotのメソッド使う
  config.include FactoryBot::Syntax::Methods

  # DBきれいにする
  config.before :suite do
    DatabaseRewinder.clean_all
  end

  # system specでheadless chrome使う
  config.before(:each) do |example|
    if example.metadata[:type] == :system
      driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
    end
  end

  # config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.use_transactional_fixtures = true

  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!
end
21
12
0

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
21
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?