Rails Rspec 单元测试 验证接口 返回格式 所有字段

Rails Rspec:单元测试API接口字段验证
本文介绍如何在Rails Rspec中进行单元测试,重点是验证API接口返回的数据格式及其所有字段。通过一个具体的例子展示了如何使用headers、put请求及预期响应来测试接口'/api/v1/tester/aaa',确保返回的employment实体数据与预期相符。


如何在单元测试中测试接口返回的字段?

如果我们有一个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: "test@example.com",
   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)

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值