【问题标题】:Ruby - Airbourne Rspec API testingRuby - Airbourne Rspec API 测试
【发布时间】:2019-03-13 00:13:22
【问题描述】:

我正在尝试编写一个 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,也无法在网上找到任何东西。

【问题讨论】:

    标签: ruby-on-rails ruby api rspec rspec-rails


    【解决方案1】:

    您正在使用 airborne,它使用 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
    

    【讨论】:

    • 我尝试在测试中使用 get 但我不确定如何使用身份验证。我应该在通话中使用用户名和密码。卷曲看起来像这样“curl example.com/api/v2/tests.json \ -v -u test@gmail.com:Abcd1234”
    • @Jane 我已经更新了我的答案以包含基本身份验证。
    • 我尝试使用相同的格式进行发布和删除,删除似乎不起作用。我收到 401 未经授权的错误。任何指针?发布工作正常。
    • 嗯,删除和发布方法应该是一样的。会不会是 API 方面的问题?
    • 我用法拉第试了一下,删除了法拉第的作品。但是对于法拉第,我似乎无法使用 Airborne expect_status 或任何其他似乎与您建议使用 rest_client 的代码一起使用的断言
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多