auth-hmacfunction测试问题

我想在我的api应用程序中使用这个gem https://github.com/seangeo/auth-hmac/

我有一个关于为请求validation创建测试的问题。 我想用hmac签署请求,但rails controller在下一个代码后没有http头

def setup #load from fixture @client = clients(:client_2) end def sign_valid_request(request,client) auth_hmac = AuthHMAC.new(client.key => client.secret ) auth_hmac.sign!(request,client.key) request end def test_response_client_xml @request = sign_valid_request(@request,@client) get :index , :api_client_key => @client.key , :format=> "xml" @xml_response = @response.body assert_response :success assert_select 'id' , @client.id.to_s end 

路由有这样的配置

 scope '/:token/' do # route only json & xml format constraints :format=> /(json|xml)/ do resources :clients, :only => [:index] end end 

我在function测试方面遇到了同样的问题。 要使用AuthHMAC正确签署每个请求,您应该在test_helper.rb中添加以下内容

 def with_hmac_signed_requests(access_key_id, secret, &block) unless ActionController::Base < ActionController::Testing ActionController::Base.class_eval { include ActionController::Testing } end @controller.instance_eval %Q( alias real_process_with_new_base_test process_with_new_base_test def process_with_new_base_test(request, response) signature = AuthHMAC.signature(request, "#{secret}") request.env['Authorization'] = "AuthHMAC #{access_key_id}:" + signature real_process_with_new_base_test(request, response) end ) yield @controller.instance_eval %Q( undef process_with_new_base_test alias process_with_new_base_test real_process_with_new_base_test ) end 

然后在你的function测试中:

 test "secret_method should be protected by an HMAC signature" do with_hmac_signed_requests(key_id, secret) do get :protected_method assert_response :success end end 

你可以尝试这个解决方案

  def sign_valid_request(request,client) auth_hmac = AuthHMAC.new(client.key => client.secret ) auth_hmac.sign!(request,client.key) # because this would be deleted in request.recycle! method in test framework request.env.merge!(request.env['action_dispatch.request.parameters']) request end 

由于Rails 3测试单元框架而在此处添加的行request.env.merge!(request.env['action_dispatch.request.parameters'])将从action_dispatch.request删除所有值。

你可以在这里找到这种行为: https : //github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb#L404