2017-03-24 61 views
0

我想爲我的Rails 5 API服務器設置RSpec測試。服務器使用active_model_serializers (0.10.5)和JSON API適配器。使用RSpec的活動模型序列化器反序列化無效文檔

從我所知道的,服務器在爲有效的JSON:

{ 
    "data": [{ 
    "id": "1", 
    "type": "categories", 
    "attributes": { 
     "name": "Language" 
    } 
    }, { 
    "id": "2", 
    "type": "categories", 
    "attributes": { 
     "name": "Ruby" 
    } 
    }, { 
    "id": "3", 
    "type": "categories", 
    "attributes": { 
     "name": "HTML" 
    } 
    }] 
} 

這裏是我的設置:

應用程序/控制器/ categories_controller.rb

def index 
    @categories = Category.all 

    render json: @categories 
    end 

應用程序/串行/category_serializer.rb

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 
end 

規格/請求/ 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"}}]} 

我缺少的是讓解串器的工作?

回答

0

在這種情況下,您不需要使用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)