DEV Community

Dmitry Salahutdinov for Amplifr.com

Posted on

Concerns testing with anonymous controller

Once you have a controller concern like this:

module BillingErrorRescuer
  extend ActiveSupport::Concern

  included do
    rescue_from Billing::LimitExceeded, with: :rescue_billing_limits

    def rescue_billing_limits
      render status: 402, json: Billing::PlanPresenter.new(@account).to_json
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

The idea is to test is separately in anonymous controller:

require 'spec_helper'

describe BillingErrorRescuer, type: :controller do
  controller do
    include BillingErrorRescuer

    def action
      @account = FactoryBot.create :account
      raise Billing::LimitExceeded
    end
  end

  before do
    routes.draw { get :action, to: "anonymous#action" }
    get :action
  end

  let(:account) { create :account, state: :trial }

  it 'renders json with billing data' do
    expect(response.body).to match_json_schema('controllers/billing_error_rescuer')
  end
end
Enter fullscreen mode Exit fullscreen mode

What does this test do?

  1. Enables testing controller features in rspec
  2. Defines anonymous controller to include concern extension
  3. Draw the route for the action
  4. Calls the action with the default controller pipeline

Thats it!
Thanks rspec-rails gem, that we have almost everything out of the box!

Top comments (0)