1
0

More than 1 year has passed since last update.

【🔴RSpecエラー】「Docker」+「Rails6」環境で、request(コントローラー)テスト時に発生する「403」エラーについて

Last updated at Posted at 2022-04-16

✅当方の環境

  • 開発環境 : Docker
  • ruby 2.7.5
  • rails 6.1.5

✅Gemの内容(必要なもののみ)

Gemfile
<中略>

group :development, :test do
  gem 'pry-rails'
  gem "rspec-rails", "~> 4.0.1"
  gem 'factory_bot_rails', '~> 5.0'
end

<中略>

group :test do
  gem 'capybara', '~> 3.28'
  gem 'selenium-webdriver', '~> 3.142'
  # gem 'webdrivers', '~> 4.1' 
 #「webdrivers」は、Docker上では使用しません。(以前は、chromedriver-helperという名称)
end

<中略>

✅ エラー内容

  • 「bundle exec rspec」コマンドのエラー内容
Failure/Error: expect(response).to have_http_status(200)
expected the response to have status code 200 but it was 403

✅エラー発生箇所

app\spec/requests/food_enquete_spec.rb
get food_enquetes_path
expect(response).to have_http_status(200)

✅解決法

  • 「rails_helper.rb」を修正する
app\spec\rails_helper.rb
ENV['RAILS_ENV'] ||= 'test' #修正前
ENV['RAILS_ENV'] = 'test' #修正後

✅エラー原因

実は、RSpec時は「development」環境でテストを実行していたから、エラーが発生した。

  • そのため、モデルテストでは「development」環境のデータベースにてデータの登録を行っていた。
  • なぜ「development」環境でテストが実行されているのかというと、「Dockerfile」または「docker-compose.yml」に「RAILS_ENV=development」に環境変数を設定しているから
  • 自身の環境変数を確認したい場合は、「echo $RAILS_ENV」で確認できる。(rails Cの場合は、「.echo $RAILS_ENV」)
  • RSpec時の実行する環境の判断は、「app\spec\rails_helper.rb」で行っており、環境変数が設定されていれば、その設定でテストを実行。
  • 環境変数がなければ、「RAILS_ENV=test」として、テストを実行する
  • それが「ENV['RAILS_ENV'] ||= 'test'」コードである。
1
0
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
1
0