Skip to content

Instantly share code, notes, and snippets.

@ondrejbartas
Created August 30, 2012 10:45
Show Gist options
  • Save ondrejbartas/3526110 to your computer and use it in GitHub Desktop.
Save ondrejbartas/3526110 to your computer and use it in GitHub Desktop.
Make sessions work in Rack::Test with Sinatra's sessions
# Put this in your test helper file
# This works when using the default Sinatra sessions (i.e. enable :sessions)
# (helper preamble not included)
require 'securerandom'
class Test::Unit::TestCase
include Rack::Test::Methods
def app
Sinatra::Application # or the name of your modular app
end
def setup_session(data = {})
sid = SecureRandom.hex(32)
hsh = data.merge("session_id" => sid)
data = [Marshal.dump(hsh)].pack('m')
secret = app.session_secret
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
str = "#{data}--#{hmac}"
set_cookie("rack.session=#{URI.encode_www_form_component(str)}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment