-
-
Save as181920/7b5d573ca02d59bad453 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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