7

一个相关的问题 意味着我可以在我的集成测试中使用令牌身份验证来测试请求,如下所示:

get "/v1/sites", nil, :authorization => "foo"
assert_response :success

出于某种原因,标题不会进入我的应用程序:

get "/v1/sites", nil, :authorization => "foo"
assert_match response.headers, /foo/

Expected {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-UA-Compatible"=>"chrome=1", "WWW-Authenticate"=>"Token realm=\"Application\"", "Content-Type"=>"text/html; charset=utf-8", "Cache-Control"=>"no-cache", "X-Request-Id"=>"23915302-9cfe-424d-86fe-5d60bc0d6b2c", "X-Runtime"=>"0.054857", "Content-Length"=>"27"} to match /foo/.

授权标头没有通过,我可以在将 athrow response.headers放入控制器时确认。当我用例如 curl 进行测试时,我确实看到了标题。在那里我什至可以设置令牌并获得访问权限。来自控制器的相关代码是:

module V1
  class SitesController < ApplicationController
    before_filter :restrict_access, :only => :index

    def index
      head :success
    end

    private
    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
        token == "foo"
      end
    end
  end 
end

这是在 Rails 4 上使用 Rails-API的 minitest

作为参考,这里是中间件堆栈,它比大多数默认的 Rails 应用程序要苗条得多。

use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x992cd28>
use Rack::Runtime
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use ActionDispatch::ParamsParser
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
run MyApp::Application.routes
4

2 回答 2

6

Just for reference. Everything was right, I was just being stupid and testing the wrong thing while debugging:

assert_match response.headers, /foo/

Is obviously false, because this is the response. Correct is to test the request

get "/v1/sites", nil, :authorization => %{Token token="foo"}
assert_includes request.headers["HTTP_AUTHORIZATION"], "foo"

This passes just fine.

于 2013-08-12T14:30:49.723 回答
0

您可以在执行请求之前在请求对象上设置标头。

request.env['HTTP_AUTHORIZATION'] = 'foo'
get '/v1/sites'
assert_response :success
于 2013-08-12T09:26:11.777 回答