Skip to content

Commit

Permalink
Cleaned up and corrected F.A.Q. section on testing HTTP Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
karmi committed Dec 23, 2010
1 parent fa416ec commit fa9bbef
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions faq.markdown
Expand Up @@ -340,7 +340,7 @@ II. When you want to protect only certain URLs in the application, or want the a
How do I test HTTP authentication? {#test_http_auth}
----------------------------------

Assuming you have this simple implementation of HTTP authentication in your application:
Assuming you have this simple implementation of HTTP authentication in your `application.rb`:

require 'rubygems'
require 'sinatra'
Expand All @@ -353,40 +353,43 @@ Assuming you have this simple implementation of HTTP authentication in your appl
"You're welcome"
end

You can test it like this:
You can test it like this with [_Rack::Test_](https://github.com/brynary/rack-test):

ENV['RACK_ENV'] = 'test'

require 'rubygems'
require 'sinatra'
require 'sinatra/test/unit'
require 'test/unit'
require 'rack/test'

require 'application'
require 'base64'

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

def app
Sinatra::Application
end

def test_without_authentication
get '/protected'
assert_equal 401, @response.status
assert_equal 401, last_response.status
end

def test_with_bad_credentials
get '/protected', {}, {'HTTP_AUTHORIZATION' => encode_credentials('go', 'away')}
assert_equal 401, @response.status
authorize 'bad', 'boy'
get '/protected'
assert_equal 401, last_response.status
end

def test_with_proper_credentials
get '/protected', {}, {'HTTP_AUTHORIZATION'=> encode_credentials('admin', 'admin')}
assert_equal 200, @response.status
assert_equal "You're welcome", @response.body
end

private

def encode_credentials(username, password)
"Basic " + Base64.encode64("#{username}:#{password}")
authorize 'admin', 'admin'
get '/protected'
assert_equal 200, last_response.status
assert_equal "You're welcome", last_response.body
end

end


<!--
### <a id='queue' href='#queue'>How do I process jobs in the background?</a>
Expand Down

0 comments on commit fa9bbef

Please sign in to comment.