Rack::BackDoor
Inject a user into a session for integration and controller tests.
Inspired by thoughtbot's clearance gem
Installation
Add this line to your application's Gemfile:
gem 'rack-back_door'And then execute:
$ bundleOr install it yourself as:
$ gem install rack-back_doorUsage
By default, Rack::BackDoor will handle the following URL:
http://example.com?as=1
By injecting 1 into the session as user_id
session[:user_id] # => 1Setup in Rails tests
Add the middleware to your stack in the config/environments/test.rb file
# config/environments/test.rb
MyApplication::Application.configure do |config|
# ...
config.middleware.use Rack::BackDoor
# ...
endSetup in Sinatra Tests
Add to your sinatra application:
# app.rb
class MySinatraApplication < Sinatra::Base
enable :sessions
use Rack::BackDoor if environment == :test
# ...
endIf you use rspec you may prefer to inject middleware only for rspec tests:
Put into spec/spec_helper.rb:
# spec/spec_helper.rb
MySinatraApplication.configure do
use Rack::BackDoor
endConfiguration
You can configure the following:
-
session_key- The key used to hold theuser_idin the session -
url_parameter- The query parameter the middleware will use as theuser_idvalue
When configured with these values and passed the following URL
The middleware will set the session like so
session[:user] #=> 1To configure the middleware in a sinatra app:
# app.rb
class MySinatraApplication < Sinatra::Base
enable :sessions
if environment == "test"
use Rack::BackDoor, session_key: "user", url_parameter: "login"
end
# ...
endTo configure the middleware in a rails app:
# config/test.rb
MyApplication::Application.configure do |config|
# ...
config.middleware.use "Rack::BackDoor", session_key: "user", url_parameter: "login"
# ...
endAdditionally, you can override the middleware to alter the rack request any
way you see fit by configuring the middleware with a block.
For instance, in sinatra:
use Rack::BackDoor do |env, user_id|
env['my.user'] = User.find(user_id)
endContributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request