0

我有一个使用 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

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

4

1 回答 1

0

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

# make a request in order to get tokens
post(
  api_user_session_path,
  params: {
    email: "foo@bar.com",
    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
于 2018-09-05T12:38:39.073 回答