|
TestingRoleRequirement
OverviewAdding Functional tests to your controllers to test your authentication is easy and powerful with the RoleRequirementTestHelper. RoleRequirement uses a special "hijacking" approach to test your controllers, to provide the most accurate testing. It removes the target controller action, puts it aside, and puts its own "stub" method in place. Then, it executes the request right through the controller using "get", to checks to see if the action's code was actually called or not. Then, after the test, it puts the original method back in place and everything as was. This approach to testing provides a more realistic and reliable method of telling whether or not your controller security is working. Steps
require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'test_help' class Test::Unit::TestCase ... include AuthenticatedTestHelper # You may have already included this include RoleRequirementTestHelper ... end
class Admin::ListingsControllerTest < Test::Unit::TestCase fixtures :users, :roles, :roles_users ... end
# :quentin is the label for a fixture in users.yml, with no admin access assert_user_can_access(:quentin, "index") assert_user_cant_access(:quentin, "destroy", :listing_id => 1) # :admin is a user as well, but has the "admin" role. assert_user_can_access(:admin, "destroy", :listing_id => 1)
assert_users_access(
{:admin => true, :quentin => false}, # admin can access, but quentin can't
"destroy", # test the destroy action
:listing_id => 1 # in each test, pass listing_id = 1 to params
)
|
Sign in to add a comment
should read fixtures :users, :roles, :roles_users
good catch, thanks.
Tim,
I installed this in an app where we have 'UserAccount?' instead of 'User'. Your code is looking for 'current_user', but AuthenticatedSystem is using 'current_user_account' for the current user.
I fixed this with the following hack in ApplicationController?:
def current_user
endPlease update your code for non-standard installations by changing the method call in RoleRequirement to match the "user" class name or generate my hack above into ApplicationController?.
Otherwise, good job!
Has anyone done testing of RoleRequirement with RSpec?