RSPEC测试RESTCLIENT :: request.execute:任何查看请求的方法



我正在使用RESTCLIENT GEM构建API客户端,并且对API的调用是通过此方法处理的

  def call(api_name,api_endpoint,token = nil,*extra_params)
    endpoint = fetch_endpoint(api_name,api_endpoint)
    params = {}
    endpoint['params'].each_with_index { |p,i| params[p] = endpoint['values'][i] }
    puts params
    if token.nil? then
      response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], params: params.to_json)
    else
      response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], headers: {"Authorization" => "Bearer #{token}"}, params: params.to_json)
    end
    response
  end

您可能会看到,我所做的就是安装一个带有呼叫的参数/值的哈希,并调用RestClient::Request#execute以获取响应。

碰巧我的一些测试,例如这个测试

it 'request_autorization' do
  obj = SpotifyIntegration.new
  response = obj.call('spotify','request_authorization',nil,state: obj.random_state_string)
  myjson = JSON.parse(response.body)
  expect(myjson).to eq({})
end

正在返回400 Bad request错误,我真的不知道为什么。其他测试,例如这个

it 'my_playlists (with no authorization token)' do
  obj = SpotifyIntegration.new
  expect {
    response = obj.call('spotify','my_playlists')
  }.to raise_error(RestClient::Unauthorized,'401 Unauthorized')
end

通过相同方法处理,运行完美。

有什么办法可以查看发送的请求?我的意思是,看看坐着/将我的请求发送到相应的API是如何安装的?可能是我能理解正在发生的事情的方式。

"请参阅请求",我的意思是

puts RestClient::Request.prepared_request

puts RestClient::Request.prepared_url

我已经搜索了RESTCLIENT文档,但没有发现类似的文档,但是也许有些人知道该怎么做。

您可以尝试使用RestClient.log获取更多信息。类似:

RestClient.log = STDOUT

WebMock也是HTTP请求的绝佳测试框架。休息客户本身的测试可以大量使用Webmock。

相关内容

最新更新