Grape caving

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 methods end end 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 :).

+4
source share
1 answer

the comments mentioned in this issue should help you, this is how even Grape checks its assistants,

https://github.com/intridea/grape/blob/master/spec/grape/endpoint_spec.rb#L475 (If the code does not exist on one line due to changes, just do ctrl + f and find helpers)

Here is some code from the same file

 it 'resets all instance variables (except block) between calls' do subject.helpers do def memoized @memoized ||= params[:howdy] end end subject.get('/hello') do memoized end get '/hello?howdy=hey' last_response.body.should == 'hey' get '/hello?howdy=yo' last_response.body.should == 'yo' end 
+2
source

Source: https://habr.com/ru/post/1480248/


All Articles