【发布时间】:2017-08-17 19:18:37
【问题描述】:
我正在尝试为我的 Rails 5 API 服务器设置 RSpec 测试。服务器使用带有 JSON API 适配器的active_model_serializers (0.10.5)。
据我所知,服务器正在提供有效的 JSON:
{
"data": [{
"id": "1",
"type": "categories",
"attributes": {
"name": "Language"
}
}, {
"id": "2",
"type": "categories",
"attributes": {
"name": "Ruby"
}
}, {
"id": "3",
"type": "categories",
"attributes": {
"name": "HTML"
}
}]
}
这是我的设置:
app/controllers/categories_controller.rb
def index
@categories = Category.all
render json: @categories
end
app/serializers/category_serializer.rb
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name
end
spec/requests/categories_spec.rb
describe 'GET /categories' do
before do
@category1 = FactoryGirl.create(:category)
@category2 = FactoryGirl.create(:category)
get '/categories'
json = ActiveModelSerializers::Deserialization.jsonapi_parse!(response.body)
@category_ids = json.collect { |category| category['id'] }
end
it 'returns all resources in the response body' do
expect(@category_ids).to eq([@category1.id, @category2.id])
end
it 'returns HTTP status ok' do
expect(response).to have_http_status(:ok)
end
end
以下是我运行bundle exec spec时遇到的错误:
ActiveModelSerializers::Adapter::JsonApi::Deserialization::InvalidDocument:
Invalid payload (Expected hash): {"data":
[{"id":"55","type":"categories","attributes":{"name":"feed"}},
{"id":"56","type":"categories","attributes":{"name":"bus"}}]}
让反序列化器工作我缺少什么?
【问题讨论】:
标签: ruby-on-rails json ruby rspec active-model-serializers