メインコンテンツまでスキップ

bypass_rescueの使用

rescue_from ステートメントで宣言されているカスタムのエラー処理だけでなく、Railsのデフォルトのエラー処理を回避するために bypass_rescue を使用します。

これにより、例外が上流でどのように扱われているかにかかわらず、発生している例外の詳細を指定できます。

Background

Given a file named "spec/controllers/gadgets_controller_spec_context.rb" with:

class AccessDenied < StandardError; end

class ApplicationController < ActionController::Base
rescue_from AccessDenied, :with => :access_denied

private

def access_denied
redirect_to "/401.html"
end
end

Standard exception handling using rescue_from

Given a file named "spec/controllers/gadgets_controller_spec.rb" with:

require "rails_helper"

require 'controllers/gadgets_controller_spec_context'

RSpec.describe GadgetsController, type: :controller do
before do
def controller.index
raise AccessDenied
end
end

describe "index" do
it "redirects to the /401.html page" do
get :index
expect(response).to redirect_to("/401.html")
end
end
end

When I run rspec spec/controllers/gadgets_controller_spec.rb

Then the examples should all pass.

Bypass rescue_from handling with bypass_rescue

Given a file named "spec/controllers/gadgets_controller_spec.rb" with:

require "rails_helper"

require 'controllers/gadgets_controller_spec_context'

RSpec.describe GadgetsController, type: :controller do
before do
def controller.index
raise AccessDenied
end
end

describe "index" do
it "raises AccessDenied" do
bypass_rescue
expect { get :index }.to raise_error(AccessDenied)
end
end
end

When I run rspec spec/controllers/gadgets_controller_spec.rb

Then the examples should all pass.