Skip to content

RSpec integration

Roman Samoilov edited this page Mar 19, 2024 · 1 revision

Rage exposes the following methods to allow you to test your API endpoints:

  get(path, params: {}, headers: {})
  options(path, params: {}, headers: {})
  head(path, params: {}, headers: {})

  post(path, params: {}, headers: {}, as: nil)
  put(path, params: {}, headers: {}, as: nil)
  patch(path, params: {}, headers: {}, as: nil)
  delete(path, params: {}, headers: {}, as: nil)

Additionally, the have_http_status matcher is available to test the response status.

This API is only available inside the request specs after requiring rage/rspec.

Examples

Testing the response

require "rage/rspec"

RSpec.describe Api::V1::PhotosController, type: :request do
  describe "#index" do
    it "returns all photos" do
      get "/api/v1/photos", headers: { "Authorization" => "Bearer my-test-token" }

      expect(response).to have_http_status(:ok)
      expect(response.parsed_body.count).to eq(5)
    end
  end
end

Submitting JSON data

require "rage/rspec"

RSpec.describe Api::V1::PhotosController, type: :request do
  describe "#create" do
    it "creates a photo" do
      post "/api/v1/photos", params: { data: "...", caption: "..." }, as: :json
      expect(response).to have_http_status(:created)
    end

    it "returns newly created photo" do
      post "/api/v1/photos", params: { data: "...", caption: "..." }, as: :json
      expect(response.parsed_body["data"]).to be_present
    end
  end
end

Testing subdomain constrained requests

require "rage/rspec"

Rage.routes.draw do
  namespace "api/v1" do
    resources :photos, constraints: { subdomain: "api" }
  end
end

RSpec.describe Api::V1::PhotosController, type: :request do
  before { host! "api.example.com" }

  it "returns all photos" do
    get "/api/v1/photos"

    expect(response).to have_http_status(:ok)
    expect(response.parsed_body.count).to eq(5)
  end
end
Clone this wiki locally