loading...
Amplifr.com

Concerns testing with anonymous controller

dsalahutdinov profile image Salahutdinov Dmitry ・1 min read

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

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

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!

Posted on Oct 10 '18 by:

dsalahutdinov profile

Salahutdinov Dmitry

@dsalahutdinov

Lead backend developer (Ruby) at Amplifr, testing fan, simplicity propagandist Family man, nature-lover, mathematician, red car driver

Amplifr.com

The easiest way to publish and analyze content on social media for media companies, e-commerce and small businesses.

Discussion

markdown guide