I have a Rails app with Grape API.
The interface is implemented using the Backbone API and the Grape API, which provides all the data.
Everything that it returns is user-specific material, so I need a link to the current user.
A simplified version looks like this:
API initialization:
module MyAPI class API < Grape::API format :json helpers MyAPI::APIHelpers mount MyAPI::Endpoints::Notes end end
End point:
module MyAPI module Endpoints class Notes < Grape::API before do authenticate! end
API helper:
module MyAPI::APIHelpers # @return [User] def current_user env['warden'].user end def authenticate! unless current_user error!('401 Unauthorized', 401) end end end
So, as you can see, I get the current user from Warden, and it works great. But the problem is testing.
describe MyAPI::Endpoints::Notes do describe 'GET /notes' do it 'it renders all notes when no keyword is given' do Note.expects(:all).returns(@notes) get '/notes' it_presents(@notes) end end end
How can I remove the helpers method * current_user * with a specific user?
I tried:
- the env / request setting, but it does not exist until the get method is called.
- stubbing MyAPI :: APIHelpers # current_user method with Mocha
- stubbing MyAPI :: Endpoints :: Notes.any_instance.stub with Mocha
Edit: At the moment, it is thinning out as follows:
Specification:
# (...) before :all do load 'patches/api_helpers' @user = STUBBED_USER end
specifications / patches / api_helpers.rb:
STUBBED_USER = FactoryGirl.create(:user) module MyAPI::APIHelpers def current_user STUBBED_USER end end
But that is definitely not the answer :).