2013-05-11 5 views
3

포도 API가있는 Rails 앱이 있습니다.스터 빙 포도 도우미

인터페이스는 백본으로 이루어지며 포도 API는 모든 데이터를 제공합니다.

반환되는 모든 것은 사용자 관련 항목이므로 현재 로그인 한 사용자에 대한 참조가 필요합니다.

단순화 된 버전은 다음과 같습니다

API 초기화 :

module MyAPI 
    class API < Grape::API 
    format :json 

    helpers MyAPI::APIHelpers 

    mount MyAPI::Endpoints::Notes 
    end 
end 

엔드 포인트 :

module MyAPI 
    module Endpoints 
    class Notes < Grape::API 
     before do 
     authenticate! 
     end 

     # (...) Api methods 
    end 
    end 
end 

API 도우미가 :

module MyAPI::APIHelpers 
    # @return [User] 
    def current_user 
    env['warden'].user 
    end 

    def authenticate! 
    unless current_user 
     error!('401 Unauthorized', 401) 
    end 
    end 
end 

그래서, 같은 당신이 볼 수있는, 나는 현재의 U를 얻는다. 교도관의 하인이 잘 작동합니다. 그러나 문제는 테스트입니다.

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 

나는 일부 특정 사용자와 헬퍼의 방법 * CURRENT_USER * 스텁 어떻게해야합니까? ENV/요청을 설정

  • 하지만 방법을 얻을 호출하기 전에 존재하지 않습니다

    나는 시도했다. 모카
  • 모카와 MyAPI :: 끝점 :: Notes.any_instance.stub 스텁과
  • 스텁 MyAPI :: APIHelpers 번호의 CURRENT_USER 방법
  • 편집

:

: 순간은,이 방법을 스텁 것

사양 :

# (...) 
    before :all do 
    load 'patches/api_helpers' 
    @user = STUBBED_USER 
    end 
    # (...) 

사양/패치/api_helpers.rb :

STUBBED_USER = FactoryGirl.create(:user) 
module MyAPI::APIHelpers 
    def current_user 
    STUBBED_USER 
    end 
end 

하지만 확실히 대답은 아닙니다. :) 당신에게 도움이 될이 issue에서 언급

답변

2

코멘트, 그것은 코드로 인해 변경에 같은 줄에이없는 경우

https://github.com/intridea/grape/blob/master/spec/grape/endpoint_spec.rb#L475

(그냥 CTRL + F & 모습을, 그것이 헬퍼 얼마나 심지어 포도 테스트입니다 헬퍼)에 대한

여기에 같은 파일에서 일부 코드는

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 
관련 문제