A related question 意味着我可以使用令牌身份验证来测试请求 综合测试如下:
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/.
授权标头无法通过,我可以在控制器中放置throw 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
作为参考,这里是中间件堆栈,它比大多数默认的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
答案 0 :(得分:5)
仅供参考。一切都是正确的,我在调试时只是愚蠢而且测试错误的东西:
assert_match response.headers, /foo/
显然是假的,因为这是响应。正确的是测试请求
get "/v1/sites", nil, :authorization => %{Token token="foo"}
assert_includes request.headers["HTTP_AUTHORIZATION"], "foo"
这传递得很好。
答案 1 :(得分:0)
您可以在执行请求之前在请求对象上设置标题。
request.env['HTTP_AUTHORIZATION'] = 'foo'
get '/v1/sites'
assert_response :success