RSpec 测试 RestClient::Request。执行:有什么方法可以查看请求?

RSpec tests for RestClient::Request.execute: Any way to see the request?

我正在使用 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

如您所见,我所做的只是使用 parameters/values 为调用安装哈希并调用 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

用同样的方法处理,运行完全没问题。

有什么办法可以看到发送的请求吗?我的意思是,看看RestClient是如何mount/sending把我的请求对应到API的?可能这样我就可以理解发生了什么。

"see the request" 我的意思是

puts RestClient::Request.prepared_request

puts RestClient::Request.prepared_url

我搜索了 RestClient 文档,没有找到类似的东西,但也许你们中的一些人知道如何做到这一点。

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

RestClient.log = STDOUT

WebMock 也是一个很好的 HTTP 请求测试框架。 rest-client本身的测试大量使用了WebMock。