Search code examples
ruby-on-railsrubyapirspecrspec-rails

Ruby - Airbourne Rspec API testing


I am trying to write an api test but I can't figure out how to do it. I converted curl to ruby and got a block like below

require 'net/http'
require 'uri'

uri = URI.parse("https://example.com/api/v2/tests.json")
request = Net::HTTP::Get.new(uri)
request.basic_auth("[email protected]", "Abcd1234")

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

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

I wrote the test as below

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

My question how do i use the api call to test this. Should i add it in a separate file or in the same file above describe. I haven't worked with Ruby before and couldn't find anything online as well.


Solution

  • You are using airborne which uses rest_client to make API calls. In order to use airborne's matchers (expect_json, etc), you need to make your API call inside the test. This means you your test should look like:

    describe 'Test to GET' do
      it 'should return 200' do
        authorization_token = Base64.encode64('[email protected]: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