用于 API 的 RSpec 匹配器集合
Collection of RSpec matchers for your API.
Add to your Gemfile:
group :test do
gem 'api_matchers'
# Optional: for JSON Schema validation
gem 'json_schemer'
endOr install manually:
gem install api_matchersInclude the matchers in your RSpec configuration:
# spec/spec_helper.rb or spec/rails_helper.rb
RSpec.configure do |config|
config.include APIMatchers::RSpecMatchers
endThen use them in your specs:
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
endVerifies the presence of a node in JSON, with optional value matching.
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)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)…Use including_text to check if a node's value contains specific text:
…including - Check if array contains an element…including_all - Check if array contains all specified elements…The matcher automatically handles Date, DateTime, and Time comparisons:
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"))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 nullSame API as have_json_node, but for XML:
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)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 = '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)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 = '
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")A generic matcher that works with either JSON or XML based on configuration:
# 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.
Compare entire JSON structures for exact equality:
…Validate JSON against a JSON Schema. Requires the json_schemer gem.
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)…schema_json = '{"type": "object", "required": ["id"]}'
expect('{"id": 1}').to match_json_schema(schema_json)……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) # exclusiveMinimumschema = {
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_nameschema = {
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)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}Check for specific HTTP status codes using either numeric codes or symbolic names:
# 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)Check if the response status is in the 2xx range:
expect(response).to be_successful # 200-299
expect(response).to be_success # alias
# Negation
expect(response).not_to be_successfulCheck if the response status is in the 3xx range:
expect(response).to be_redirect # 300-399
expect(response).to be_redirection # aliasCheck for client (4xx) or server (5xx) errors:
expect(response).to be_client_error # 400-499
expect(response).to be_server_error # 500-599Convenience matchers for common status codes:
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 # 204Verify that JSON contains specific keys at the root or at a given path:
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)Verify the type of a JSON value at a given path:
…Check the
暂无开放 Issues,或尚未同步最近议题。