【问题标题】:Rails 3.2.13: API Integration Test with Authorization FailureRails 3.2.13:授权失败的 API 集成测试
【发布时间】:2015-11-18 17:53:59
【问题描述】:

我正在尝试为我编写的 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 中调用的 authenticate 方法是:

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 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 integration-testing


    【解决方案1】:

    试试:

    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的信息。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2021-08-14
      相关资源
      最近更新 更多