RSpec 的活动模型序列化程序反序列化无效文档

Active Model Serializers deserialization invalid document with RSpec

我正在尝试为我的 Rails 5 API 服务器设置 RSpec 测试。服务器使用 active_model_serializers (0.10.5) 和 JSON API 适配器。

据我所知,服务器正在提供有效 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"}}]}

为了使反序列化器工作,我缺少什么?

您不需要在此上下文中使用 ActiveModel 反序列化器。对于您的测试,只需执行以下操作:

  parsed_response = JSON.parse(response.body)
  expect(parsed_response['data'].size).to eq(2)
  expect(parsed_response['data'].map { |category| category['id'].to_i })
    .to eq(Category.all.map(&:id))
  expect(response.status).to eq(200)