forked from doorkeeper-gem/doorkeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
Testing protected controllers
felipeelias edited this page Feb 5, 2012
·
1 revision
Few things you should be aware of when testing controllers protected by doorkeeper.
in the majority of cases, you'll only need to stub the doorkeeper_token method in you controller:
describe Api::V1::ProfilesController do
describe 'GET #index' do
let(:token) { stub :accessible? => true }
before do
controller.stub(:doorkeeper_token) { token }
end
it 'responds with 200' do
get :index, :format => :json
response.status.should eq(200)
end
end
endStubbing :accessible? => true will bypass the doorkeeper filter, since the token is valid. If you prefer to return false then the response status will be 401 unauthorized.
If you have an action that requires a specific scope, you will need to stub the token scope:
# controllers/api/v1/profiles_controller.rb
class Api::V1::ProfilesController < ApiController
doorkeeper_for :create, :scopes => [:write]
# ...
def create
respond_with 'api_v1', Profile.create!(params[:profile])
end
end
# spec/controllers/api/v1/profiles_controller_spec.rb
describe 'POST #create (with scopes)' do
let(:token) do
stub :accessible? => true, :scopes => [:write]
end
before do
controller.stub(:doorkeeper_token) { token }
end
it 'creates the profile' do
Profile.should_receive(:create!) { stub_model(Profile) }
post :create, :format => :json
response.status.should eq(201)
end
endIf you need to test the controller fully integrated with your app, you'll need to create the necessary models:
describe Api::V1::CredentialsController do
describe 'GET #me (integrated)' do
let!(:application) { Factory :application } # OAuth application
let!(:user) { Factory :user }
let!(:token) { Factory :access_token, :application => application, :resource_owner_id => user.id }
it 'responds with 200' do
get :me, :format => :json, :access_token => token.token
response.status.should eq(200)
end
it 'returns the user as json' do
get :me, :format => :json, :access_token => token.token
response.body.should == user.to_json
end
end
endFor more examples, check the doorkeeper provider app on Github here.