【问题标题】:Active Model Serializers deserialization invalid document with RSpecActive Model Serializers 使用 RSpec 反序列化无效文档
【发布时间】: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


    【解决方案1】:

    您无需在此上下文中使用 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多