Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

api_matchers

> 编程语言
Open source

Collection of RSpec matchers for APIs

173 stars0 likes3 views
WebsiteGitHub

About

Collection of RSpec matchers for APIs

API Matchers

Collection of RSpec matchers for your API.

Table of Contents

  • Requirements
  • Installation
  • Quick Start
  • Matchers
    • Response Body Matchers
      • have_json_node
      • have_xml_node
      • have_node
      • have_json
      • match_json_schema
    • HTTP Status Matchers
      • have_http_status
      • be_successful
      • be_redirect
      • be_client_error / be_server_error
      • Specific Status Matchers
    • JSON Structure Matchers
      • have_json_keys
      • have_json_type
    • Collection Matchers
      • have_json_size
      • be_sorted_by
    • Header Matchers
      • be_json / be_xml
      • have_header
      • have_cors_headers
      • have_cache_control
    • Pagination Matchers
      • be_paginated
      • have_pagination_links
      • have_total_count
    • Error Response Matchers
      • have_error / have_errors
      • have_error_on
    • JSON:API Matchers
      • be_json_api_compliant
      • have_json_api_data
      • have_json_api_attributes
      • have_json_api_relationships
    • HATEOAS Matchers
      • have_link
  • Configuration
  • Upgrading from 0.x to 1.0
  • Contributing

Requirements

  • Ruby 3.1+
  • RSpec 3.12+

Installation

Add to your Gemfile:

ruby
group :test do
  gem 'api_matchers'

  # Optional: for JSON Schema validation
  gem 'json_schemer'
end

Or install manually:

bash
gem install api_matchers

Quick Start

Include the matchers in your RSpec configuration:

ruby
# spec/spec_helper.rb or spec/rails_helper.rb
RSpec.configure do |config|
  config.include APIMatchers::RSpecMatchers
end

Then use them in your specs:

ruby
RSpec.describe "Users API" do
  it "returns user data" do
    get "/api/users/1"

    expect(response.body).to have_json_node(:id).with(1)
    expect(response.body).to have_json_node(:name).with("John")
    expect(response.body).to have_json_node(:email).including_text("@example.com")
  end
end

Matchers

Response Body Matchers

have_json_node

Verifies the presence of a node in JSON, with optional value matching.

Basic Usage

ruby
json = '{"user": {"id": 1, "name": "John", "active": true}}'

# Check node exists
expect(json).to have_json_node(:user)
expect(json).to have_json_node(:id)      # Works with nested nodes too

# Check node exists with specific value
expect(json).to have_json_node(:id).with(1)
expect(json).to have_json_node(:name).with("John")
expect(json).to have_json_node(:active).with(true)

# Check node does NOT exist
expect(json).not_to have_json_node(:admin)

# Check node exists but with different value
expect(json).not_to have_json_node(:id).with(999)

Deeply Nested JSON

ruby
json = '{
  "response": {
    "data": {
      "transaction": {
        "id": 12345,
        "status": "completed",
        "payment": {
          "method": "credit_card",
          "amount": 99.99
        }
      }
    }
  }
}'

# All these work - it searches recursively
expect(json).to have_json_node(:transaction)
expect(json).to have_json_node(:id).with(12345)
expect(json).to have_json_node(:status).with("completed")
expect(json).to have_json_node(:method).with("credit_card")
expect(json).to have_json_node(:amount).with(99.99)

Different Value Types

…

Partial Text Matching

Use including_text to check if a node's value contains specific text:

…

Array Matching

including - Check if array contains an element
…
including_all - Check if array contains all specified elements
…

Date and Time Values

The matcher automatically handles Date, DateTime, and Time comparisons:

ruby
json = '{"created_at": "2024-01-15", "updated_at": "2024-01-15T10:30:00+00:00"}'

expect(json).to have_json_node(:created_at).with(Date.parse("2024-01-15"))
expect(json).to have_json_node(:updated_at).with(DateTime.parse("2024-01-15T10:30:00+00:00"))

Null Values

ruby
json = '{"middle_name": null}'

expect(json).to have_json_node(:middle_name)           # Node exists (even if null)
expect(json).to have_json_node(:middle_name).with(nil) # Explicitly check for null

have_xml_node

Same API as have_json_node, but for XML:

ruby
xml = '1John'

expect(xml).to have_xml_node(:id).with("1")
expect(xml).to have_xml_node(:name).with("John")
expect(xml).to have_xml_node(:name).including_text("Jo")
expect(xml).not_to have_xml_node(:email)

Nested XML

ruby
xml = '

  success
  
    
      123
      
        John
        Doe
      
    
  

'

expect(xml).to have_xml_node(:status).with("success")
expect(xml).to have_xml_node(:id).with("123")
expect(xml).to have_xml_node(:first_name).with("John")
expect(xml).to have_xml_node(:last_name).with("Doe")

XML with Attributes

ruby
xml = 'Widget29.99'

# Check element content
expect(xml).to have_xml_node(:name).with("Widget")
expect(xml).to have_xml_node(:price).with("29.99")

# Check element exists
expect(xml).to have_xml_node(:product)
expect(xml).to have_xml_node(:price)

Partial Text in XML

ruby
xml = 'Validation failed: Email format is invalid'

expect(xml).to have_xml_node(:message).including_text("Validation failed")
expect(xml).to have_xml_node(:message).including_text("Email format")
expect(xml).not_to have_xml_node(:message).including_text("Server error")

SOAP Response Example

ruby
soap_response = '

  
    
      
        42
        johndoe
        [email protected]
      
    
  

'

expect(soap_response).to have_xml_node(:Id).with("42")
expect(soap_response).to have_xml_node(:Username).with("johndoe")
expect(soap_response).to have_xml_node(:Email).including_text("@example.com")

have_node

A generic matcher that works with either JSON or XML based on configuration:

ruby
# Default is JSON
expect('{"name": "John"}').to have_node(:name).with("John")

# Configure for XML
APIMatchers.setup do |config|
  config.have_node_matcher = :xml
end

expect('John').to have_node(:name).with("John")

Tip: If your API uses both JSON and XML, use have_json_node and have_xml_node explicitly for clarity.

have_json

Compare entire JSON structures for exact equality:

…

match_json_schema

Validate JSON against a JSON Schema. Requires the json_schemer gem.

Basic Usage

ruby
schema = {
  type: "object",
  required: ["id", "name"],
  properties: {
    id: { type: "integer" },
    name: { type: "string", minLength: 1 },
    email: { type: "string", format: "email" }
  }
}

# Valid JSON
expect('{"id": 1, "name": "John"}').to match_json_schema(schema)

# Invalid JSON - missing required field
expect('{"id": 1}').not_to match_json_schema(schema)

# Invalid JSON - wrong type
expect('{"id": "not-an-integer", "name": "John"}').not_to match_json_schema(schema)

Complex Schemas

…

Schema as JSON String

ruby
schema_json = '{"type": "object", "required": ["id"]}'
expect('{"id": 1}').to match_json_schema(schema_json)

Array Validation

…

String Formats

…

Numeric Constraints

ruby
schema = {
  type: "object",
  properties: {
    age: { type: "integer", minimum: 0, maximum: 150 },
    price: { type: "number", minimum: 0, exclusiveMinimum: true },
    quantity: { type: "integer", multipleOf: 5 },
    rating: { type: "number", minimum: 1, maximum: 5 }
  }
}

expect('{"age": 25, "price": 9.99, "quantity": 10, "rating": 4.5}').to match_json_schema(schema)
expect('{"age": -1}').not_to match_json_schema(schema)  # minimum: 0
expect('{"price": 0}').not_to match_json_schema(schema)  # exclusiveMinimum

Conditional Validation

ruby
schema = {
  type: "object",
  properties: {
    type: { type: "string", enum: ["personal", "business"] },
    company_name: { type: "string" }
  },
  if: {
    properties: { type: { const: "business" } }
  },
  then: {
    required: ["company_name"]
  }
}

expect('{"type": "personal"}').to match_json_schema(schema)
expect('{"type": "business", "company_name": "Acme Inc"}').to match_json_schema(schema)
expect('{"type": "business"}').not_to match_json_schema(schema)  # missing company_name

Pattern Matching

ruby
schema = {
  type: "object",
  properties: {
    phone: { type: "string", pattern: "^\\+?[1-9]\\d{1,14}$" },
    slug: { type: "string", pattern: "^[a-z0-9-]+$" },
    hex_color: { type: "string", pattern: "^#[0-9A-Fa-f]{6}$" }
  }
}

expect('{"phone": "+14155551234", "slug": "my-post", "hex_color": "#FF5733"}').to match_json_schema(schema)

Error Messages

When validation fails, you get detailed error messages:

Expected JSON to match schema.
Errors:
  - value at `/name` is not a string at name
  - object at root is missing required properties: email

Response: {"id":1,"name":123}

HTTP Status Matchers

have_http_status

Check for specific HTTP status codes using either numeric codes or symbolic names:

ruby
# Using numeric codes
expect(response).to have_http_status(200)
expect(response).to have_http_status(201)
expect(response).to have_http_status(404)

# Using symbolic names (Rails-style)
expect(response).to have_http_status(:ok)
expect(response).to have_http_status(:created)
expect(response).to have_http_status(:not_found)
expect(response).to have_http_status(:unprocessable_entity)

# Negation
expect(response).not_to have_http_status(:ok)

be_successful

Check if the response status is in the 2xx range:

ruby
expect(response).to be_successful  # 200-299
expect(response).to be_success     # alias

# Negation
expect(response).not_to be_successful

be_redirect

Check if the response status is in the 3xx range:

ruby
expect(response).to be_redirect    # 300-399
expect(response).to be_redirection # alias

be_client_error / be_server_error

Check for client (4xx) or server (5xx) errors:

ruby
expect(response).to be_client_error  # 400-499
expect(response).to be_server_error  # 500-599

Specific Status Matchers

Convenience matchers for common status codes:

ruby
expect(response).to be_not_found           # 404
expect(response).to be_unauthorized        # 401
expect(response).to be_forbidden           # 403
expect(response).to be_unprocessable       # 422
expect(response).to be_unprocessable_entity # alias for 422
expect(response).to be_no_content          # 204

JSON Structure Matchers

have_json_keys

Verify that JSON contains specific keys at the root or at a given path:

ruby
json = '{"id": 1, "name": "John", "email": "[email protected]"}'

# Check for multiple keys
expect(json).to have_json_keys(:id, :name, :email)
expect(json).to have_json_keys(:id, :name)  # subset is OK

# At a specific path
json = '{"user": {"id": 1, "name": "John"}}'
expect(json).to have_json_keys(:id, :name).at_path("user")

# Negation
expect(json).not_to have_json_keys(:password, :token)

have_json_type

Verify the type of a JSON value at a given path:

…

Collection Matchers

have_json_size

Check the

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言