Search code examples
ruby-on-railsrspeccancan

Are there any advantages to testing unauthorized-by-cancan actions at the controller level, or is this superfluous?


Say I have the following CanCan abilities defined

can :index, Project
cannot :show, Project

and an ability_spec

it { is_expected.to have_abilities([:index], Project }
it { is_expected.to not_have_abilities([:show], Project }

are there any situations where it is advantageous to test the unauthorized action at the controller level, or is this superfluous?

describe "GET #show" do
  it "raises Access Denied" do 
    expect { 
      get :show, { id: subject.id} 
    }.to raise_error(CanCan::AccessDenied)
  end
end

Solution

  • I would say that just having your ability configuration specs is fine since that exercises your app's business logic. The functionality of raising a CanCan::AccessDenied error when an ability is unauthorised to perform an action is specced in the CanCan library itself.

    If you had your own custom error classes that you were using when access is denied, then I think the case could probably be made to write the kind of controller specs you've mentioned.