---
title: 'Faster Tests: Sign In Through The Back Door'
teaser:
tags: web,ruby,rails,open source,clearance
author: Dan Croak
published_on: 2012-12-14
---

One way to make tests faster is to no load and submit the sign in form during
the [setup
phase](https://thoughtbot.com/blog/post/32455387133/four-phase-test).

This [back door](http://xunitpatterns.com/back%20door.html) inserts Rack
middleware into a Rails app that uses
[Clearance](http://github.com/thoughtbot/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](http://mislav.uniqpath.com/rails/haxor-backdoor-in-development/)
except Rack middleware works with Rails routing constraints.

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