2013-05-11 175 views
3

我有葡萄API的Rails應用程序。Stubbing葡萄幫手

該接口使用Backbone完成,而Grape 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 

所以,你可以看到,我得到目前的你從Warden的服務,它工作正常。但問題在於測試。

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 :: APIHelpers#CURRENT_USER方法與摩卡
  • 磕碰MyAPI ::端點:: Notes.any_instance.stub與摩卡

編輯: 目前,它的存根這樣:

規格:

# (...) 
    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