Skip to content

Instantly share code, notes, and snippets.

@as181920
Forked from promisedlandt/test_helper.rb
Last active August 29, 2015 14:20
Show Gist options
  • Save as181920/7b5d573ca02d59bad453 to your computer and use it in GitHub Desktop.
Save as181920/7b5d573ca02d59bad453 to your computer and use it in GitHub Desktop.
class PolicyTest < ActiveSupport::TestCase
def assert_permissions(current_user, record, available_actions, permissions_hash = {})
permissions_hash.each do |action, should_be_permitted|
if should_be_permitted
assert_permit current_user, record, action
else
refute_permit current_user, record, action
end
end
# Make sure all available actions were tested
unused_actions = @available_actions - permissions_hash.keys
assert unused_actions.empty?, "The following actions were not tested: #{ unused_actions }"
# Make sure tested actions were in available_actions
unavailable_actions = permissions_hash.keys - @available_actions
assert unavailable_actions.empty?, "The following actions were tested, but not in available_actions: #{ unavailable_actions }"
end
def assert_permit(current_user, record, action)
assert permit(current_user, record, action), "User #{ current_user } should be permitted #{ action } on #{ record }, but isn't permitted"
end
def refute_permit(current_user, record, action)
refute permit(current_user, record, action), "User #{ current_user } should NOT be permitted #{ action } on #{ record }, but is permitted"
end
def permit(current_user, record, action)
self.class.to_s.gsub(/Test/, "").constantize.new(current_user, record).public_send("#{ action.to_s }?")
end
end
require "test_helper"
class UserPolicyTest < PolicyTest
before do
@user = create(:user)
@available_actions = [:index, :new, :create, :edit, :update, :edit_organization]
end
test "admin user" do
assert_permissions(create(:admin), @user, @available_actions,
create: true,
index: true,
new: true,
edit: true,
update: true,
edit_organization: true)
end
test "user on his own record" do
assert_permissions(@user, @user, @available_actions,
create: true,
index: true,
new: true,
edit: true,
update: true,
edit_organization: false)
end
# non logged in user, user on foreign record, organization admin user, etc.
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment