Rails Rspec 單元測試 驗證接口 返回格式 所有字段


如何在單元測試中測試接口返回的字段?

如果我們有一個api的entity爲 employment.rb

# frozen_string_literal: true

module API::Entities::BorrowerEntities
  class Employment < API::Entity
    param :in_type_id, safe_path: %i[primary_income_source id]
    param :aaa_type, safe_path: %i[employed_code]
    param :started_with_employer, safe_path: %i[started_with_employer]
  end
end


 let(:default_headers) { { 'CONTENT_TYPE' => 'application/json' } }

it 'xxx xxx' do

  headers = { 'Authorization' => bearer_token_for(xixi.account) }.merge(default_headers)

  put '/api/v1/tester/aaa', sample_entity_with('aaa_type' => 'Self-aaa').to_json, headers

  expected_presenter = API::Entities::BorrowerEntities::Employment.represent(tester.account.current_aaa_detail)

  expect(response_body).to eq(JSON.parse(expected_presenter.to_json))

end

 

詳細的例子:

Grape API Entity has a "represent" method that can be useful in specs scenarios when we expect some object to be presented with some specific entity, for example when we have:

present user, with: API::Entities::User

We are actually saying:

API::Entities::User.represent(current_user) and this will give us an object like this:
#<API::Entities::User:0x00007fe6aab82868
 @object=
  #<User:0x00117fe6aab82ee8
   id: 35345,
   name: "Test",
   email: "[email protected]",
   created_at: Mon, 14 Oct 2019 21:57:54 UTC +00:00,
   updated_at: Mon, 14 Oct 2019 21:57:54 UTC +00:00,
 @options={}>

Then in our spec scenario, we can call to_json from here and use it as a expected from the response of an API call like:
get '/api/v3/user'
expected_json = API::Entities::User.represent(current_user).to_json
expect(response.body).to eq(expected_json)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章