Search code examples
ruby-on-railsrubyrspecdevisecancan

Rspec + Cancan error


admin_spec.rb

it "checks access for user" do
  visit rails_admin_path
  login(:user) #helper method
  expect(page).to raise_error(CanCan::AccessDenied)
end

console output

Failure/Error: login(:user)
CanCan::AccessDenied:
  You are not authorized to access this page.

But test still is red. Why and how fix it?


Solution

  • Have you taken a look at this article?

    Testing abilities in CanCan

    Instead of actually visiting the URL, maybe you can use the can? method to determine if the :user is allowed to visit the rails admin path.

    I'm assuming you're using Devise? If so, I found this other SO article that may be helpful. They suggest including a block to allow devise test helpers.

    Alternatively, switch to CanCanCan (that's what we currently use) and it works MUCH easier (since CanCan is no longer supported):

      context 'sign_in' do
        scenario 'with valid information should redirect to the administration dashboard', :js => true do
          sign_in_with sign_in_url, registered_user.email, 'validpassword', 'admin_user'
    
          expect(page).to have_content('Site Administration')
        end
    
        scenario 'with invalid information', :js => true do
          sign_in_with sign_in_url, registered_user.email, 'invalidvalidpassword', 'admin_user'
          expect(page).to have_content('Invalid email or password')
        end
      end