Written by Sean Behan on Thu Aug 22nd 2013

Assume you have your standard Sinatra application.

# app.rb
require 'sinatra' 

configure do
    enable :sessions
end

get '/' do
    if session[:user_id]
        "OK"
    else
        raise "NOT OK!"
    end
end

To test this you need to make a request with the 'rack.session' key populated with the session values you want. This can be tedious to add to all the requests you make in your test suite.

The solution is to make a request in the setup method which will run before each test is executed.

This way you can remove the duplication in the tests but have control over what goes in the session.

# app_test.rb

require 'test/unit'
require 'rack/test'

require 'app'

class CurrentUserSession < Test::Unit::TestCase
    include Rack::Test::Methods

    def app
        Sinatra::Application
    end

    def current_user_session
        get '/', {}, { 'rack.session' => { user_id: current_user.id } }
    end

    def current_user
        User.find_or_create_by(full_name: "Sean Behan")
    end

    def setup
        current_user_session
    end
end

class UserTest < CurrentUserSession
     def test_index
        get "/"

        assert_equal current_user.id, last_request.env['rack.session']['user_id']
        assert last_response.ok?
    end
end

You can fork this gist


Tagged with..
#Sinatra #Testing #Rack

Just finishing up brewing up some fresh ground comments...