moustafasamir
2/14/2016 - 8:49 AM

Rspec_controller_authorization.rb

# I think authorization needs to be done mainly for **controllers** to make sure your authorization is working correctly with your controllers. So to make it **DRY** you can implement your own `matcher` to be used like this 

    let!(:user) {create :user}
    before { login_user_request user}

    it "grants admin access to show action" do
      expect{ get :show, {id: user.id} }.to be_authorized
    end
    it "denies user access to edit action" do
      expect{ get :edit, {id: user.id} }.to be_un_authorized
    end

# and then implement these matchers with your own way to test how a request will be authorized or not

    RSpec::Matchers.define :be_authorized do
      match do |block|
        block.call
        expect(response).to be_success
      end
   
      def supports_block_expectations?
        true
      end
    end
    
    RSpec::Matchers.define :be_un_authorized do
      match do |block|
        expect{
          block.call
        }.to raise_error(Pundit::NotAuthorizedError)
      end
    
      def supports_block_expectations?
        true
      end
    end