Skip to content

Instantly share code, notes, and snippets.

@davidbody
Created December 20, 2011 16:37
Show Gist options
  • Save davidbody/1502205 to your computer and use it in GitHub Desktop.
Save davidbody/1502205 to your computer and use it in GitHub Desktop.
Rails admin_only!
class ApplicationController < ActionController::Base
protect_from_forgery
def admin_only!
if user_signed_in?
unless current_user.admin?
flash[:error] = "The feature you attempted to use is restricted to admins only."
redirect_to root_url
end
else
flash[:error] = "You must be signed in to use this feature."
redirect_to root_url
end
end
end
require 'spec_helper'
describe ApplicationController do
include Devise::TestHelpers
describe "#admin_only!" do
before do
controller.response = ActionController::TestResponse.new
end
context "when not logged in" do
before do
sign_out :user
end
it "redirects to the root url" do
controller.should_receive(:redirect_to).with(root_url)
controller.admin_only!
end
it "displays an appropriate error message" do
controller.admin_only!
flash[:error].should == "You must be signed in to use this feature."
end
end
context "when logged in as non-admin user" do
before do
user = Factory(:user)
sign_in user
end
it "redirects to the root url" do
controller.should_receive(:redirect_to).with(root_url)
controller.admin_only!
end
it "displays an appropriate error message" do
controller.admin_only!
flash[:error].should == "The feature you attempted to use is restricted to admins only."
end
end
context "when logged in as admin user" do
it "does not redirect" do
user = Factory(:user, :admin => true)
sign_in user
controller.should_not_receive(:redirect_to)
controller.admin_only!
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment