带机架保护的Rspec测试API

带机架保护的Rspec测试API,api,session,rspec,rack,grape,Api,Session,Rspec,Rack,Grape,我正试图用rspec集成(请求)测试来测试我的API 我在浏览器中转到位于0.0.0.0:3000/api/regions的api端点,它返回我的数据,我得到一个会话id,看起来一切正常 我在API中使用机架保护: module Api class Root < Grape::API use Rack::Protection, instrumenter: ActiveSupport::Notifications use Rack::Protection::Authe

我正试图用rspec集成(请求)测试来测试我的API

我在浏览器中转到位于
0.0.0.0:3000/api/regions
的api端点,它返回我的数据,我得到一个会话id,看起来一切正常

我在API中使用机架保护:

module Api
  class Root < Grape::API
     use Rack::Protection, instrumenter: ActiveSupport::Notifications
     use Rack::Protection::AuthenticityToken    
     prefix  'api'

     helpers do
        def warden
          request.env['warden']
        end
     end

     version 'v1', using: :header, vendor: 'vendor', strict: false do
        mount Resources::V1::Search => '/'
        mount Resources::V1::Regions => '/'
     end    

   end
end
下面是一个测试:

describe Resources::V1::Regions do
  describe 'GET /regions' do
    it 'returns some data' do
      get '/api/regions'
      [... expectations - doesn't get here...]
    end
  end
end
以下是错误:

 RuntimeError:
       you need to set up a session middleware *before* Rack::Protection::RemoteToken
     # ./spec/requests/api/region_spec.rb:6:in `block (3 levels) in <top (required)>'
这在这里引起了:

我怀疑我不需要
使用Rack::Session::Cookie
,因为当服务器加载时,其他的东西正在这样做,但是我需要添加一些东西来让测试工作。不知道那是什么东西

如果您需要任何其他信息,请告诉我

版本:

  • 葡萄(0.6.1)
  • 轨道(4.0.2)
  • 机架保护(1.5.2)
  • rspec(2.14.1)

我通过在请求的第三个参数中添加'rack.session'散列来解决这个问题,即
get'/api/regions',{},{'rack.session'=>{}

但我找到了更好的方法: 它增加了会话,同时解决了典狱长问题

RSpec.configure do |config|
[...]
  rack_app = Module.new do 
    def app
      @app ||= Rack::Builder.new do
        use Rack::Session::Cookie
        Warden::Manager.serialize_into_session { |user| user.id }
        Warden::Manager.serialize_from_session { |id| User.get(id) }
        use Warden::Manager do |manager|
          manager.default_strategies :password, :basic
          # manager.failure_app = Acme::BadAuthentication
        end
        run Api::Root
      end
    end
  end

  config.include rack_app, type: :request
  end
除非有人有更好的答案,否则就做记号作为答案

 RuntimeError:
       you need to set up a session middleware *before* Rack::Protection::RemoteToken
     # ./spec/requests/api/region_spec.rb:6:in `block (3 levels) in <top (required)>'
undefined method `each' for #<ActionDispatch::Request::Session:0x7f7bf9e521e0 not yet loaded>
RSpec.configure do |config|
[...]
  rack_app = Module.new do 
    def app
      @app ||= Rack::Builder.new do
        use Rack::Session::Cookie
        Warden::Manager.serialize_into_session { |user| user.id }
        Warden::Manager.serialize_from_session { |id| User.get(id) }
        use Warden::Manager do |manager|
          manager.default_strategies :password, :basic
          # manager.failure_app = Acme::BadAuthentication
        end
        run Api::Root
      end
    end
  end

  config.include rack_app, type: :request
  end