2
votes

I am working on a Ruby on Rails project using ActiveAdmin and Cancancan. I defined some abilities for role users like super_administrator, administrator or subscribers.

After writing some units tests I discovered than abilities where not working properly and I can't figured out what is wrong.

Concretely, I have a Newsletter module and I want only administrator or super_administrator to manage it.

Here is my ability excerpt:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # visitor user (not logged in)

    alias_action :create, :read, :update, :destroy, to: :crud

    if user.super_administrator?
      # super_administrator privileges
    elsif user.administrator?
      # administrator privileges
    elsif user.subscriber?
      cannot :manage, Newsletter
    else
      cannot :destroy, :all
      cannot :update, :all
      cannot :create, :all
      cannot :manage, Newsletter
    end
  end
end

My tests:

# this test breaks for no reason
test 'should not destroy newsletter if logged in as subscriber' do
  sign_in @subscriber
  assert_no_difference 'Newsletter.count' do
    delete :destroy, id: @newsletter
  end
  assert_redirected_to admin_dashboard_path
end

private

def initialize_test
  @newsletter = newsletters(:one)
  @subscriber = users(:alice)
end

This test breaks because Newsletter is destroyed even if I wrote the ability for subscriber to not manage Newsletter.

What is weird as well is if I test abilities for subscriber, everything works:

# this test pass as expected by ability
test 'should test abilities for subscriber' do
  sign_in @subscriber
  ability = Ability.new(@subscriber)
  assert ability.cannot?(:create, Newsletter.new), 'should not be able to create'
  assert ability.cannot?(:read, Newsletter.new), 'should not be able to read'
  assert ability.cannot?(:update, Newsletter.new), 'should not be able to update'
  assert ability.cannot?(:destroy, Newsletter.new), 'should not be able to destroy'
end 

I tried to manually test directly in browser and Abilities are not working either.

I don't understand what I missed. Does someone has any clue about what is wrong on my code ?

My Project:

  • Ruby 2.2.2
  • Rails 4.2.3
  • ActiveAdmin 1.0.0 pre1
  • Cancancan 1.12.0
1
Can you post the full code or else branch from the ability class in the constructor?adamliesko
I updated my first question to add visitor's ability. I precise I debugged abilities putting some logger.debug message in the subscriber section and they were appearing in the terminal which mean user and role are properly set but not applied.anthony

1 Answers

0
votes

After investigating for hours and hours, I discovered the problem was coming from variables having the same name as ActiveAdmin one's (with correct abilities) and was overriding them (with bad abilities).
Changing variables name in my ApplicationController fixed all bugs with Abilities.