Faster Tests: Sign In Through The Back Door

Dan Croak

One way to make tests faster is to no load and submit the sign in form during the setup phase.

This back door inserts Rack middleware into a Rails app that uses Clearance:

# config/environments/test.rb
class ClearanceBackDoor
  def initialize(app)
    @app = app
  end

  def call(env)
    @env = env
    sign_in_through_the_back_door
    @app.call(@env)
  end

  private

  def sign_in_through_the_back_door
    if user_id = params['as']
      user = User.find(user_id)
      @env[:clearance].sign_in(user)
    end
  end

  def params
    Rack::Utils.parse_query(@env['QUERY_STRING'])
  end
end

MyRailsApp::Application.configure do
  # ...
  config.middleware.use ClearanceBackDoor
  # ...
end

Then, include a user in an as parameter in integration tests:

visit root_path(as: user)

It works for any URL:

visit new_feedback_path(as: giver)

This is like to Mislav’s approach except Rack middleware works with Rails routing constraints.

On one project using this technique, the total test suite time was reduced 23%.