LoginSignup
0
1

More than 1 year has passed since last update.

#Rails で 存在しない全てのパスへの GET / POST / PUT / PATCH / DELETE / OPTIONS リクエストで 404 NotFound を返すようにエラーハンドリングする

Last updated at Posted at 2019-12-01

注意

結構怖い
非推奨

方法

routes.rb の 最下部 でこうだ
上の方に書くと優先マッチしてダークホールになってしまうかも

match '*path', to: 'errors#not_found', via: :all

一個ずつメソッドを書く場合はこう

  get '*path', to: 'errors#not_found'
  post '*path', to: 'errors#not_found'
  put '*path', to: 'errors#not_found'
  patch '*path', to: 'errors#not_found'
  delete '*path', to: 'errors#not_found'
  match '*path', to: 'errors#not_found', via: :options

rspec でのテスト

こんなんで

require 'rails_helper'

describe 'not found path', type: :request do
  describe 'get' do
    subject { get "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end

  describe 'post' do
    subject { post "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end

  describe 'put' do
    subject { put "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end

  describe 'patch' do
    subject { patch "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end

  describe 'delete' do
    subject { delete "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end

  context 'options' do
    subject { process :options, "/path/to/not/existence/" }

    before { subject }

    it { expect(response.status).to eq 404 }
  end
end

多分これで行けるはず

REf

Railsの ActionController::RoutingError は ApplicationController での rescue_from で捕まえられない - Qiita

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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