我无法针对我的jsonapi-resources
Rails 5.1 API 测试 POST 请求。Rails 似乎不允许我自定义请求内容类型,或者做错了。
jsonapi-resources
版本 0.9.0,边缘 Rails(我认为它是 5.2 beta2)
所以,这个 IntegrationTest 代码:
require 'test_helper'
class EventsControllerTest < ActionDispatch::IntegrationTest
setup do
@event = events(:one)
end
test 'should get index' do
get events_url, as: 'application/vnd.api+json'
assert_response :success
end
test 'should create event' do
assert_difference('Event.count') do
post events_url, params: {
data: {
type: 'events',
attributes: {
name: @event.name,
body: @event.body
}
}
},
as: :api_json
end
assert_response 201
end
end
...产生此错误:
$ bin/rails test
...
Failure:
EventsControllerTest#test_should_create_event [/Users/aljabear/Projects/visualist/test/controllers/events_controller_test.rb:26]:
...
GET 请求工作正常。POST 请求失败。在 POST 请求之后打印出 @request.body 给出了以下线索:
{
"errors":[
{"title":"Bad Request",
"detail":"765: unexpected token at 'data[type]=events\u0026data[attributes][name]=Book+1\u0026data[attributes][body]=This+is+body+text.'",
"code":"400",
"status":"400"
}
]
}
所以,很明显:api_json
,Rails 不尊重内容类型;我猜它是在吐出编码后的表单 URL。
如果我这样做,并打印结果:
...
as: :json,
headers: {
'Content-type': 'application/vnd.api+json',
}
...
我得到以下信息,表明jsonapi-resources
行为正常(非常严格);当我使用时as: :json
,Rails 正确地将内容格式化为json
,而不是在我使用时:api_json
。
{
"errors":[{
"title":"Not acceptable",
"detail":"All requests must use the 'application/vnd.api+json' Accept without media type parameters. This request specified 'application/json'.",
"code":"406",
"status":"406"
}]
}
Rails 只是不按要求转换 MIME 类型吗?或者这只是一个序列化问题?我怎样才能强迫它这样做?谢谢...欢迎任何线索。