设计测试助手无法登录

问题描述 投票:0回答:1

我有一个使用devise_token_auth的rails API应用程序,在我的测试中(minitest)我需要发送POST请求并签名用户,所以我使用了sign_in方法,但它似乎没有做任何事情。

这是我的测试文件

require 'test_helper'

class ActivityControllerTest < ActionDispatch::IntegrationTest
    include Devise::Test::IntegrationHelpers
    test "post activity" do
        sign_in users('one')
        post '/activity/', params: {
            original_activity_log_file: fixture_file_upload('files/test_gpx.gpx', 'application/gpx'),
            title: 'test activity',
            description: 'test description'
        }
        assert_response 200
    end
end

这是运行时的结果

Expected response to be a <200: OK>, but was a <401: Unauthorized>
Response body: {"errors":["You need to sign in or sign up before continuing."]}.
Expected: 200
  Actual: 401

可能会发生什么导致测试失败?

ruby-on-rails ruby devise minitest devise-token-auth
1个回答
0
投票

您正在使用devise_token_auth,在这种情况下,普通设计帮助程序不起作用,您需要使用发布请求执行普通授权。这是一个例子:

# make a request in order to get tokens
post(
  api_user_session_path,
  params: {
    email: "[email protected]",
    password: "password"
  }.to_json,
  headers: {
    'Content-Type' => 'application/json',
    'Accept' => 'application/json'
  }
)
# fetch data from response
client = response.headers['client']
token = response.headers['access-token']
expiry = response.headers['expiry']
token_type = response.headers['token-type']  
uid = response.headers['uid']  
auth_params = {
  'access-token' => token,
  'client' => client,
  'uid' => uid,
  'expiry' => expiry,
  'token_type' => token_type
}
new_client = users('one')
get(
  api_find_client_by_name_path(new_client.name),
  headers: auth_params
)               
assert_response :ok
© www.soinside.com 2019 - 2024. All rights reserved.