Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
AuthTestHelper provides methods to test authentication
module AuthTestHelper
def verify_authentication_declared
verify_no_actions_duped_in_authorization_declarations
verify_all_actions_declare_authorization
end
def verify_all_actions_declare_authorization
all_actions = default_controller_class.action_methods.to_a.map(&:to_sym)
declared_actions = find_declared_actions(:authenticate) + find_declared_actions(:do_not_authenticate)
missing_actions = all_actions - declared_actions
raise "#{default_controller_class.to_s}: Missing authentication declaration for #{missing_actions.map(&:inspect).join(", ")}" if missing_actions.any?
end
def verify_no_actions_duped_in_authorization_declarations
duped_actions = find_declared_actions(:authenticate) & find_declared_actions(:do_not_authenticate)
raise "#{default_controller_class.to_s}: Duplicated authentication declaration for #{duped_actions.map(&:inspect).join(", ")}" if duped_actions.any?
end
def verify_all_actions_declare_authorization
all_actions = default_controller_class.action_methods.to_a.map(&:to_sym)
declared_actions = find_declared_actions(:authenticate) + find_declared_actions(:do_not_authenticate)
missing_actions = all_actions - declared_actions
raise "#{default_controller_class.to_s}: Missing authentication declaration for #{missing_actions.map(&:inspect).join(", ")}" if missing_actions.any?
end
def verify_do_not_require_authenticate(*expected_actions)
match_fields(:do_not_authenticate, expected_actions)
end
def verify_require_authenticate(*expected_actions)
match_fields(:authenticate, expected_actions)
end
def match_fields(callback_name, expected_actions)
actual_actions = find_declared_actions(callback_name)
res = (expected_actions - actual_actions)
raise_match_error(res, callback_name) if res.any?
true
end
def default_controller_class
determine_default_controller_class(to_s)
end
def find_declared_actions(callback_name)
callback = find_callback(callback_name)
if callback.respond_to?(:options)
callback.options[:only]
else
[]
end
end
def raise_match_error(res, callback_name)
message_modifier = callback_name =~ /not/ ? "not " : " "
raise "#{default_controller_class.to_s}: Should #{message_modifier}require authenticate failed
expected actions #{expected_actions.map(&:inspect).join(", ")}
did not match actual actions #{actual_actions.map(&:inspect).join(", ")}"
end
def find_callback(filter)
default_controller_class._process_action_callbacks.detect{|f| f.filter == filter} || []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment