Skip to content

Testing: Controller tests

David Wessman edited this page Jan 19, 2016 · 1 revision

A controller test should test your actions when

  1. User is not authenticated
  2. User is authenticated

I try to use this in two contexts. To mock authentication you use the allow_user_to :manage, Foo method which is defined in spec/support/controller_macros.rb.

Example controller test:

require 'rails_helper'

RSpec.describe FooController, type: :controller do
  context 'when not allowed to' do
    describe 'GET #index' do
      it 'returns http forbidden' do
        get :index
        response.should have_http_status(:forbidden)
      end
    end
  end

  context 'when allowed to manage foo' do
    allow_user_to :manage, Foo # This tells cancan that the current user is allowed to manage foo

    describe 'GET #index' do
      it 'succeeds' do
        get :index
        response.should be_success
      end
    end
  end
end