DEV Community

Dmitry Salahutdinov for Amplifr.com

Posted on

12 7

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay