2010-08-12 68 views
3

我正在尝试使用基本身份验证进行测试签名。我尝试了一些方法。请参阅下面的代码以获取失败的尝试和代码列表。有什么明显的我做错了。谢谢集成测试具有基本身份验证的Rails API

class ClientApiTest < ActionController::IntegrationTest 
    fixtures :all 

    test "adding an entry" do 

    # No access to @request 
    #@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("[email protected]:qwerty123") 

    # Not sure why this didn't work 
    #session["warden.user.user.key"] = [User, 1] 

    # This didn't work either 
    # url = URI.parse("http://localhost.co.uk/diary/people/1/entries.xml") 
    # req = Net::HTTP::Post.new(url.path) 
    # req.basic_auth '[email protected]', 'qwerty123' 

    post "/diary/people/1/entries.xml", {:diary_entry => { 
               :drink_product_id => 4, 
               :drink_amount_id => 1, 
               :quantity => 3 
              }, 
             } 
    puts response.body 
    assert_response 200 
    end 
end 
+0

Je sse的回答是正确的。你应该标记答案是正确的。 – 2011-03-25 19:57:03

回答

6

它看起来像你可能正在运行rails3 - Rails3切换到Rack :: test,所以语法是不同的。你传入一个环境哈希以设置你的请求变量,比如标题。

试着这么做:

path = "/diary/people/1/entries.xml" 
params = {:diary_entry => { 
    :drink_product_id => 4, 
    :drink_amount_id => 1, 
    :quantity => 3} 

env=Hash.new 
env["CONTENT_TYPE"] = "application/json" 
env["ACCEPT"] = "application/json" 
env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("[email protected]:qwerty123") 

get(end_point, params, env) 

这可能是工作太多,但它可能是一个西纳特拉唯一的事情:

get '/protected', {}, {'HTTP_AUTHORIZATION' => encode_credentials('go', 'away')} 

Sinatra test credit

+0

我们如何为Rails3进行Digest身份验证? – 2011-08-07 23:21:58

4

这个工作对我来说在Rails 3的

@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('username', 'password') 
get :index 
+1

这在集成测试中不起作用,因为@请求不可用(在原始问题中提及)。 – jstr 2014-11-06 01:43:04