LoginSignup
0
0

More than 1 year has passed since last update.

RSpecの"GET #show"で[:ok]のはずが[:found]となってしまった話

Posted at

概要

request specの"GET #show"にてリクエストが成功するかテストを行なってみたところ、HTTPステータスコードが200(:ok)を期待したが、302(:found)が結果として出力された。

ターミナル
$ bundle exec rspec spec/requests/recipes_spec.rb

# ===== 省略 =====

GET #show
    レシピIDを渡してリクエストを投げたとき
      リクエストが成功する (FAILED - 1)

Failures:

  1) Recipes GET #show レシピIDを渡してリクエストを投げたとき リクエストが成功する
     Failure/Error: expect(response).to have_http_status(:ok)
       expected the response to have status code :ok (200) but it was :found (302)
     # ./spec/requests/recipes_spec.rb:33:in `block (4 levels) in <main>'

結論

config.include Devise::Test::IntegrationHelpers, type: :requestを追加してDeviseのヘルパーを使えるようにする。

spec/rails_helper.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods

  # ===== Deviseのヘルパーを使えるようにする設定するため、ここを追加 =====
  config.include Devise::Test::IntegrationHelpers, type: :request
  
  # ===== 省略 =====
end

example内の get(recipe_path(recipe.id))よりも前sign_in userを追加する。

spec/requests/recipes_spec.rb
RSpec.describe "Recipes", type: :request do

  # ===== 省略 =====
  
  describe "GET #show" do
    context "レシピIDを渡してリクエストを投げたとき" do
      let(:user) { create(:user) }
      let(:recipe) { create(:recipe) }
      it "リクエストが成功する" do
        sign_in user  # ===== これを追加 =====
        get(recipe_path(recipe.id))
        expect(response).to have_http_status(:ok)
      end
    end
  end
end

原因

なぜ、302(:found)が結果として出力されたのか。
それはapplication_controller.rbに記述しているauthenticate_user!が原因だった。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  
  # ===== 省略 =====
end

このメソッドが働いて"#show"にアクセスする前にログインページへリダイレクトされてしまった。
その結果、302(:found)が吐き出されたのだ。

以上です。
指摘箇所がありましたら、ご教授いただけますと幸いです。

参考

0
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
0
0