title: Stubbing Grape helper
body: <p>I have Rails app with Grape API.</p>
  
  <p>The interface is done with Backbone and Grape API provides it all data.</p>
  
  <p>All it returns is user-specific stuff, so i need reference to currently logged in user.</p>
  
  <p>Simplified version looks like this:</p>
  
  <p>API initialization:</p>
  
  <pre><code>module MyAPI
    class API &lt; Grape::API
      format :json
  
      helpers MyAPI::APIHelpers
  
      mount MyAPI::Endpoints::Notes
    end
  end
  </code></pre>
  
  <p>Endpoint: </p>
  
  <pre><code>module MyAPI
    module Endpoints
      class Notes &lt; Grape::API
        before do
          authenticate!
        end
  
        # (...) Api methods
      end
    end
  end
  </code></pre>
  
  <p>API helper:</p>
  
  <pre><code>module MyAPI::APIHelpers
    # @return [User]
    def current_user
      env['warden'].user
    end
  
    def authenticate!
      unless current_user
        error!('401 Unauthorized', 401)
      end
    end
  end
  </code></pre>
  
  <p>So, as you can see, i get the current user from Warden and it works fine. But the problem is with testing.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>How can I stub helpers's method *current_user* with some specific user? </p>
  
  <p>I tried:</p>
  
  <ul>
  <li>setting env/request, but it doesn't exist before calling <em>get</em> method.</li>
  <li>stubbing MyAPI::APIHelpers#current_user method with Mocha</li>
  <li>stubbing MyAPI::Endpoints::Notes.any_instance.stub with Mocha</li>
  </ul>
  
  <p>Edit:
  At the moment, it's stubbed this way:</p>
  
  <p>spec:</p>
  
  <pre><code>  # (...)
    before :all do
      load 'patches/api_helpers'
      @user = STUBBED_USER
    end
    # (...)
  </code></pre>
  
  <p>spec/patches/api_helpers.rb:</p>
  
  <pre><code>STUBBED_USER = FactoryGirl.create(:user)
  module MyAPI::APIHelpers
    def current_user
      STUBBED_USER
    end
  end
  </code></pre>
  
  <p>But it's definitely not the answer :).</p>