ruby-on-railsruby-on-rails-3rspeccancan

How to write a CanCan rspec for a modeless controller?


I have a model group.rb and then a controller group_invitations.rb which is modeless.

GroupInvitationsController

  before_filter :find_group_by_group_id
  before_filter :authenticate_user!
  before_filter :current_ability
  authorize_resource :class => false

  def current_ability
    @current_ability ||= Ability.new(current_user, @group)
  end

When I write a rspec for this:

  it "should be able to create" do
    ability = Ability.new(nil)
    ability.should be_able_to(:create, GroupInvitation.new)
  end

Rspec then errors with:

NameError:
   uninitialized constant GroupInvitation

How do I setup rspec to test this modeless controller?


Solution

  • You need to call @ability.should be_able_to(:create, :group_invitation). You can read about what is authorized when using a model-less controller in the documentation.

    This is the relevant section:

    class ToolsController < ApplicationController
      authorize_resource :class => false
      def show
        # automatically calls authorize!(:show, :tool)
      end
    end