Rails 3.2.13:API 授权失败的集成测试

Rails 3.2.13: API Integration Test with Authorization Failure

我正在尝试为我写的 API 编写集成测试。 api 需要授权才能访问。

我正在使用 FactoryGirl,我的用户有以下工厂:

factory :user do
    name "John Doe"
    sequence(:email) { |n| "person-#{n}@testSuite.com" }
    password "password"
    password_confirmation { |u| u.password }
    api_key "1234567890"
end

在我的控制器 before_filter 中调用的身份验证方法是:

def authenticate
  authenticate_or_request_with_http_token do |token, options|
    @current_user = User.where(api_key: token).first
  end
end

而我的测试是

test 'User Index' do
    @user = FactoryGirl.create(:user)
    get '/api/v1/users', authorization: "Token token=\"#{@user.api_key}\""
    assert_response :success
end

此测试不断失败并返回 401 响应。

设置授权令牌的正确方法是什么,以便我可以实际连接到 API?

尝试:

test 'User Index' do
    @user = FactoryGirl.create(:user)
    get '/api/v1/users', nil, { "HTTP_AUTHORIZATION" => "Token token=\"#{@user.api_key}\""
    assert_response :success
end

详细了解 Get in integration tests here

您要在 header 中设置的密钥称为:HTTP_AUTHORIZATION