简体   繁体   中英

What is the best way to test application controller rescue status codes in Rails 5?

I am running into an interesting challenge this weekend. I want to test the following 4 rescue statements. What do you feel is the best approach? I have been testing anonymous controllers, gets, and more but I am coming up blank. Is this even possible?

Rspec

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ApplicationController, type: :controller do
  it 'rescue record not found with 404' do

  end

  it 'rescue parameter missing with 400' do

  end

  it 'rescue routing error with 400' do

  end

  it 'rescue invalid authenticity token with 400' do

  end
end

Application Controller

# frozen_string_literal: true

class ApplicationController < ActionController::Base
  force_ssl if: :ssl_configured?

  rescue_from ActiveRecord::RecordNotFound, with: :render_404
  rescue_from ActionController::ParameterMissing, with: :render_400
  rescue_from ActionController::RoutingError, with: :render_404
  rescue_from ActionController::InvalidAuthenticityToken, with: :render_400

  include StatusCodes
  include JsonTester

  private

  def ssl_configured?
    AppUnsecure.settings[:ssl_configured]
  end
end

As @max said, you can't test a routing error in this way since it is raised earlier in the stack than the controller.

However, as for the rest of your test cases, you can do that pretty easily:

RSpec.describe ApplicationController do
  controller do
    def test_record_not_found
      raise ActiveRecord::RecordNotFound
    end

    def test_parameter_missing
      raise ActionController::ParameterMissing, :test
    end

    def test_invalid_auth_token
      raise ActionController::InvalidAuthenticityToken
    end
  end

  before :each do
    routes.draw do
      get "test_record_not_found" => "anonymous#test_record_not_found"
      get "test_parameter_missing" => "anonymous#test_parameter_missing"
      get "test_invalid_auth_token" => "anonymous#test_invalid_auth_token"
    end
  end

  it "rescues record not found with 404" do
    get :test_record_not_found
    expect(response).to have_http_status(404)
  end

  it "rescues parameter missing with 400" do
    get :test_parameter_missing
    expect(response).to have_http_status(400)
  end

  it "rescues invalid auth token with 400" do
    get :test_invalid_auth_token
    expect(response).to have_http_status(400)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM