Replies: 2 comments 6 replies
-
Yes, that would be a good addition (actually, it's on my private TODO list for Action Policy). In one project, I used the following API: it "is allowed" do
stub_policy(PlaygroundPolicy).to allow_rule(:manage_api?).for(playground)
expect(subject).to eq playground
end
it "is not allowed" do
stub_policy(PlaygroundPolicy).to deny_rule(:manage_api?).for(playground)
expect { subject }.to raise_error(PermissionError)
end And this is the implementation: # frozen_string_literal: true
module PolicyHelpers
class Stub
attr_reader :policy, :example
def initialize(policy, example)
@policy = policy
@example = example
end
def to(matcher)
# Pass policy as local var to the block
policy = self.policy
example.instance_exec do
allow_any_instance_of(policy).to receive(matcher.rule) do |instance|
expect(instance).to matcher
matcher.value
end
end
end
end
class Matcher < RSpec::Matchers::BuiltIn::HaveAttributes
attr_reader :rule, :value
def initialize(rule, value)
@rule = rule
@value = value
super({})
end
def for(record)
@expected[:record] = record
self
end
end
def stub_policy(policy_class)
Stub.new(policy_class, self)
end
def allow_rule(rule)
Matcher.new(rule, true)
end
def deny_rule(rule)
Matcher.new(rule, false)
end
end
RSpec.configure do |config|
config.include PolicyHelpers
end The reason why it has never been upstreamed is that I had to use I hadn't had time to find a better way of handling this though. |
Beta Was this translation helpful? Give feedback.
5 replies
-
@palkan Hi! Useful thread. I'm also looking at stubbing |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I've been using
action_policy
in a number of projects at work, and have struggled with how best to set up tests where a user's authorization is mocked out.A specific issue: I have used
allowed_to?
to define what parts of a page are rendered (e.g. links to #new paths). When writing rspec examples I don't want to go through setting up a user with the correct granular abilities for each system test. Instead, I would like to use a helper function that mocks out policies/actions:Is this a feature that could be added to
action_policy
? If not, would I be able to get advice on which functions to mock out to achieve this? I have some working code at the moment, but it feels brittle as heck!Beta Was this translation helpful? Give feedback.
All reactions