Skip to content

Instantly share code, notes, and snippets.

@hgmnz
Created September 25, 2010 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hgmnz/597393 to your computer and use it in GitHub Desktop.
Save hgmnz/597393 to your computer and use it in GitHub Desktop.
# authorization matchers
module AuthorizationMatcher
class RequireAuthentication
def initialize(method, action, params, context)
@method = method
@action = action
@params = params
@context = context
end
def matches?(controller)
responds_with_redirect &&
responds_with_success_when_authenticated
end
def responds_with_redirect
do_request
@context.response.code == '302'
end
private :responds_with_redirect
def responds_with_success_when_authenticated
@context.sign_in
do_request
@context.response.code == '200'
end
private :responds_with_success_when_authenticated
def do_request
@context.__send__(@method, @action, @params )
end
private :do_request
def failure_message
"Expected #{@method} #{@action} to require authentication"
end
def negative_failure_message
"Did not expect #{@method} #{@action} to require authentication"
end
end
def require_authentication_for(method, action, params = {})
RequireAuthentication.new(method, action, params, self)
end
end
# assumes the following or similar
module SessionHelpers
def sign_in_as(user)
@controller.current_user = user
return user
end
def sign_in
sign_in_as Factory(:email_confirmed_user)
end
def sign_out
@controller.current_user = nil
end
end
# example usage in a controller
describe SomeController, 'authorization' do
it { should require_authentication_for(:get, :new) }
it { should require_authentication_for(:post, :create) }
context 'with an instance' do
# this context needed if the action will find the instance in the database
let(:something) { Factory(:something) }
it { should_not require_authentication_for(:get, :show, :id => something.id) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment