rescue_fromは下に書いたものから評価される

エラーページ をrescue_fromを使って以下のように設定しておりました。

class Foo::BarController < ApplicationController

rescue_from ActiveRecord::RecordNotFound, with: :render_404
rescue_from ActionController::RoutingError, with: :render_404
rescue_from Exception, with: :render_500
 

# 404ページをレンダリング
def render_404(exception = nil)

end

# 500ページをレンダリング
def render_500(exception = nil)

end
 
end

 

 

そしたら、httpステータス404が出るべき場所がことごとく500になってしまい、テストが落ちまくりました。。。

 $ docker-compose run --rm app bundle exec rspec

Failure/Error: expect(response).to have_http_status(404)
expected the response to have status code 404 but it was 500

 

 

原因がわからず困っていたところ、

rescue_fromは下に書いたものから評価される」ということを先輩からお聞きしました。

なので、rescue_fromの順番を上下逆に変更しました。

class Foo::BarController < ApplicationController

rescue_from Exception, with: :render_500
rescue_from ActionController::RoutingError, with: :render_404
rescue_from ActiveRecord::RecordNotFound, with: :render_404

end

 

 これでhttpステータス404が出るべきところは404が出てくれるようになり、無事テストも通るようになりました!!