Ruby - Airbourne Rspec API 测试

Ruby - Airbourne Rspec API testing

我正在尝试编写 api 测试,但我不知道该怎么做。 我将 curl 转换为 ruby 并得到如下方块

require 'net/http'
require 'uri'

uri = URI.parse("https://example.com/api/v2/tests.json")
request = Net::HTTP::Get.new(uri)
request.basic_auth("test@gmail.com", "Abcd1234")

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

我写的测试如下

describe 'Test to GET' do
  it 'should return 200' do
  
  expect_json_types(name: :string)
  expect_json(name: 'test')
    expect_status(200)
  end
end

我的问题是如何使用 api 调用来测试它。我应该将它添加到单独的文件中还是在上面描述的同一文件中。我之前没有与 Ruby 合作过,也无法在网上找到任何东西。

您正在使用 airborne which uses rest_client 拨打 API 电话。 为了使用 airborne 的匹配器(expect_json 等),您需要在测试中进行 API 调用。这意味着您的测试应该如下所示:

describe 'Test to GET' do
  it 'should return 200' do
    authorization_token = Base64.encode64('test@gmail.com:Abcd1234')
    get(
      "https://example.com/api/v2/tests.json",
      { 'Authorization' => "Basic #{authorization_token}" }
    )
    expect_json_types(name: :string)
    expect_json(name: 'test')
    expect_status(200)
  end
end