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提到应该帮助你