我进行了以下测试:
require 'rails_helper'
RSpec.describe 'User management', :type => :request do
before do
@expected_number_of_users = 3
end
context 'an authenticated user with admin privileges' do
before do
# This username/password combo is in my fixtures
@headers = login_user 'scottj', '123456'
end
context 'when at least a username, name, role, and email address are passed as inputs' do
before do
@new_user_details = {
:username => 'stitch',
:name => 'Stitch',
:role => :admin,
:email => 'stitch@disney.com'
}
end
it 'should create a new user' do
post users_path, headers: @headers, params: @new_user_details
expect(response).to have_http_status(:ok)
expect(json.username).to eq('stitch')
expect(json.name).to eq('Stitch')
expect(json.role).to eq(:admin.to_s)
expect(json.email).to eq('stitch@disney.com')
expect(json.password).to_not be_nil
end
end
end
end
带有以下login_support.rb
文件:
module LoginSupport
def json_api_headers
{
"Content-Type": 'application/json',
"Accept": 'application/json'
}
end
def login_user(username, password)
combined_login_password = username + ":" + password
encoded_username_password = Base64.encode64(combined_login_password)
headers = {
'X-Api-Key': Client.find_by_id(1234).api_key,
'Authorization': 'Basic ' + encoded_username_password
}.merge(json_api_headers)
post '/login', headers: headers
user = JSON.parse(response.body, object_class: OpenStruct)
{
'Authorization': 'Bearer ' + user.auth_token
}
end
end
此测试按预期通过,但是当我将login_user
的返回类型更改为(即,更改该函数的最后三行)时:
{
'Authorization': 'Bearer ' + user.auth_token
}.merge(json_api_headers)
现在,当我运行测试时,出现错误:
ActionDispatch::ParamsParser::ParseError: 765: unexpected token at 'username=stitch&name=Stitch&role=admin&email=jaywir3%40gmail.com'
在我看来,标头的更正确版本是这样的,因为我的API都希望以JSON形式接收POST请求的正文,并返回JSON,标头到位。在我看来,指定了这些标头的POST请求正试图将请求的主体作为查询参数传递。
我在做错什么吗?测试时,我应该只将Accept
和Content-Type
标头保留在请求之外吗?