Lockdown RSpec Helper
Want to test your application’s Lockdown rules with RSpec but don’t know how? Well, hopefully this will help. Lockdown 1.3.0 introduces an RSpec helper to take some of the pain away from testing your app. To use this helper, make the following addition to spec_helper.rb:
require 'lockdown/rspec_helper'
include Lockdown::RspecHelper
This will add in some nice helpers, but first I want to show you how to customize it. Since you probably have your own method for creating a mock user object, you may want to override the mock_user method like so:
# file spec_helper.rb
require 'lockdown/rspec_helper'
module Lockdown
module RspecHelper
def mock_user
Factory(:user)
end
end
end
include Lockdown::RspecHelperIt’s that simple. You can also do this for the mock_user_group method.
Now let me show you what that gives you. You’ll be able to test your controller access like so:
describe PostsController do
describe "as a admin user" do
before do
login_admin
end
it "should allow all access" do
allowed_actions.should == all_actions
end
end
describe "as a standard user" do
before do
login_standard
end
it "should allow access only to [:new, :create, :show]" do
allowed_actions.should == only_actions(:new, :create, :show)
end
end
describe "as a public user" do
before do
public_user
end
it "should allow access to only show" do
allowed_actions.should == only_actions(:show)
end
end
describe "with post_administrators group" do
before do
login_with_group(:post_administrators)
end
it "should allow all access" do
allowed_actions.should == all_actions
end
end
describe "with post_editors group" do
before do
login_with_group(:post_editors)
end
it "should allow access only to :show, :edit and :update" do
allowed_actions.should == only_actions(:show, :edit, :update)
end
end
end
As you can see above you get the following methods:
- login_admin
- Log in as an administrator
- login_standard
- This user will get the public_access + protected_access rights defined in init.rb
- public_user
- This user will get the public_access rights defined in init.rb
- login_with_group(*user_groups)
- This user will get the public_access + protected_access + the rights associated to the user_group(s) passed into the method.
- allowed_actions
- Returns array of access rights for the current user (defined by one of
the methods above)
- Returns array of access rights for the current user (defined by one of
- only_actions(*actions)
- Return an array of actions formatted for comparison against allowed_actions
- all_actions({})
- Return an array of all the actions available for this controller, formatted for comparison.
- Can pass in :except => [:method1, methodx] to exclude methods.
This is the first release of this so it may not match everyone’s needs right off the bat. If you have a problem, please let me know on the lighthouse lockdown account by submitting a ticket.
