def it_should_grant_access(role, options)
# ...
if except.present?
actions = DEFAULT_ACTIONS - Array(except)
elsif only.present?
actions = Array(only)
else
actions = DEFAULT_ACTIONS
end
# ...
end
def it_not_should_grant_access(role, options)
# ...
end
end
As you see from the example code there are some stuff I need to do
before I can do the actual testing.
My question is how to solve this in a DRY way so that I can use the
set up code in the “not” case as well?
Another problem is that when I specify that some role should have
access to some actions, it also means that the role should not have
access to all but those actions. This means that I must have each
request test in separate so that I can call them. But I’m not sure how
to do this.
As you see from the example code there are some stuff I need to do
before I can do the actual testing.
My question is how to solve this in a DRY way so that I can use the
set up code in the “not” case as well?
Just use the Extract Method refactoring:
def it_should_grant_access(role, options)
actions_from(options).each do |action|
# …
end
end
def it_not_should_grant_access(role, options)
actions_from(options).each do |action|
# …
end
end
def actions_from(options)
if options[:except]
DEFAULT_ACTIONS - options[:except]
elsif options[:only]
options[:only]
else
DEFAULT_ACTIONS
end
end
Another problem is that when I specify that some role should have
access to some actions, it also means that the role should not have
access to all but those actions. This means that I must have each
request test in separate so that I can call them. But I’m not sure how
to do this.
Just use one macro:
def it_should_grant_access(role, options)
actions_from(options).each do |action|
# … specify grant access
end
(DEFAULT_ACTIONS - actions_from(options)).each do |action|
# … specify deny access
end
end
def it_should_grant_access(role, options)
request_index = proc do
get :index
response.success?
end
# ...
actions_from(options).each do |action|
request = instance_eval(&eval("request_#{action}"))
request.should be_true, "#{role} should have been granted access
to #{action}, but was not"
end
# ...
end
Not perfect, but it works.
Btw, I solved the “not-case” by flipping only and except and then just
call it_should_grant_access.
Thanks!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.