Skip to content

Instantly share code, notes, and snippets.

@ambethia

ambethia/hello.rb

Created Sep 3, 2009
Embed
What would you like to do?
A contrived example of a problem I'm have testing sessions in Sinatra with Rack::Test
require 'sinatra/base'
class HelloApp < Sinatra::Base
enable :sessions
get '/' do
"Hello, #{session[:user]}"
end
post '/' do
session[:user] = params[:user]
redirect '/'
end
end
require 'test/unit'
require 'rack/test'
class HelloTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
HelloApp
end
def session
last_request.env['rack.session']
end
def test_post_demonstrating_sessions_work
post '/', { :user => "Jason" }
follow_redirect!
assert_equal "Hello, Jason", last_response.body
end
###
# These two tests below fail:
###
# Trying this the only way I've seen given as an example:
def test_get_setting_session_from_request
get '/', {}, { 'rack.session' => { :user => "Jason" } }
assert_equal "Hello, Jason", last_response.body, "'Jason' was never put in session[:user]"
end
# /shrug
def test_get_setting_session_from_request_another_way
get '/', {}, { :session => { :user => "Jason" } }
assert_equal "Hello, Jason", last_response.body, "'Jason' was never put in session[:user]"
end
end
require 'sinatra/base'
class HelloApp < Sinatra::Base
enable :sessions
get '/' do
"Hello, #{session[:user]}"
end
post '/' do
session[:user] = params[:user]
redirect '/'
end
end
require 'test/unit'
require 'rack/test'
class HelloTest < Test::Unit::TestCase
def setup
@browser = Rack::Test::Session.new(Rack::MockSession.new(HelloApp))
end
def session
last_request.env['rack.session']
end
def do_login!
@browser.post '/', { :user => "Jason" }
end
def test_post
do_login!
@browser.follow_redirect!
assert_equal "Hello, Jason", @browser.last_response.body
end
def test_get
do_login!
@browser.get '/'
assert_equal "Hello, Jason", @browser.last_response.body, "'Jason' was never put in session[:user]"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment