minitest_openapi_examples 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fbc114b36d03fefeb73291e3409d9bcac4f49766c8de36cd46eb02bbea880576
4
+ data.tar.gz: 574fcaeafa8ed30be6e96b6835dd2871d46eaab782eb58c00d4ef75071343fe3
5
+ SHA512:
6
+ metadata.gz: 8d8ea03599aeeb3f03cfbdf377357449308c0a768ad18689956640b144bc057ec8fd2ec9a8ebff8f1a6d6617bc737a3a5c63d7ef29eaa196e5deb3db0a2492e1
7
+ data.tar.gz: 0a35df0457f06f19d16d32edfab78cadc18ec2de9b31516d38bb03394ddbf3efaa7300f46e2bc13d75a70638632aac6971917a731c0417af89fe3dd132d28451
data/.idea/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Ignored default folder with query files
5
+ /queries/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
9
+ # Editor-based HTTP Client requests
10
+ /httpRequests/
@@ -0,0 +1,15 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="ModuleRunConfigurationManager">
4
+ <shared />
5
+ </component>
6
+ <component name="NewModuleRootManager">
7
+ <content url="file://$MODULE_DIR$">
8
+ <sourceFolder url="file://$MODULE_DIR$/features" isTestSource="true" />
9
+ <sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
10
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
11
+ </content>
12
+ <orderEntry type="inheritedJdk" />
13
+ <orderEntry type="sourceFolder" forTests="false" />
14
+ </component>
15
+ </module>
data/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/minitest_openapi_examples.iml" filepath="$PROJECT_DIR$/.idea/minitest_openapi_examples.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
data/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
data/.rubocop.yml ADDED
@@ -0,0 +1,31 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: disable
4
+
5
+ Style/StringLiterals:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Layout/LineLength:
14
+ Max: 120
15
+
16
+ # Keep complete test examples together.
17
+ Metrics/AbcSize:
18
+ Exclude:
19
+ - "test/**/*"
20
+
21
+ Metrics/BlockLength:
22
+ Exclude:
23
+ - "test/**/*"
24
+
25
+ Metrics/ClassLength:
26
+ Exclude:
27
+ - "test/**/*"
28
+
29
+ Metrics/MethodLength:
30
+ Exclude:
31
+ - "test/**/*"
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.2.0] - 2026-11-04
4
+
5
+ - Add opt-in CI check mode for OpenAPI examples recorded by Rails request tests.
6
+ - Report the endpoint and example key when a sanitized request or response example is missing or differs from the checked-in spec. Check mode leaves the YAML file untouched.
7
+ - Document how to enable the check in CI.
8
+
9
+ ## [0.1.0] - 2026-03-05
10
+
11
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at elizabeth.mor324@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Galiia Fattakhova
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,199 @@
1
+ # MinitestOpenapiExamples
2
+
3
+ MinitestOpenapiExamples records real request and response examples from Rails Minitest request tests, sanitizes unstable or sensitive values, and writes them into an existing OpenAPI spec.
4
+
5
+ It is designed for teams that already maintain an OpenAPI document and want to keep examples in sync with real test coverage, without switching to RSpec or adopting a large DSL.
6
+
7
+ ## Features
8
+
9
+ - Record response examples from Rails Minitest request tests
10
+ - Record request body examples for write actions
11
+ - Sanitize tokens, emails, UUIDs, timestamps, and other unstable values
12
+ - Write examples into an existing OpenAPI YAML file
13
+ - Auto-write examples during test runs, if enabled
14
+ - Run sync manually through a Rake task
15
+
16
+ ## Installation
17
+
18
+ Add the gem to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem "minitest_openapi_examples", git: "https://github.com/galiyafatt2/minitest_openapi_examples"
22
+ ````
23
+
24
+ Then run:
25
+
26
+ ```bash
27
+ bundle install
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ Configure the gem in your Rails application:
33
+
34
+ ```ruby
35
+ MinitestOpenapiExamples.configure do |config|
36
+ config.spec_path = Rails.root.join("doc/openapi.yml").to_s
37
+ config.auto_write = false
38
+ config.default_content_type = "application/json"
39
+
40
+ config.sanitizers = [
41
+ ->(value) { value.gsub(/Bearer\s+\S+/, "Bearer [FILTERED]") },
42
+ ->(value) { value.gsub(/\b[\w.%+-]+@[\w.-]+\.\w+\b/, "[FILTERED_EMAIL]") }
43
+ ]
44
+ end
45
+ ```
46
+
47
+ Include the test helper in your request test base class:
48
+
49
+ ```ruby
50
+ class ActionDispatch::IntegrationTest
51
+ include MinitestOpenapiExamples::TestHelper
52
+ end
53
+ ```
54
+
55
+ Annotate a test class with OpenAPI endpoint metadata:
56
+
57
+ ```ruby
58
+ class Api::V1::ArticlesTest < ActionDispatch::IntegrationTest
59
+ openapi_examples path: "/api/v1/articles/{id}", method: :get, operation_id: "getArticle"
60
+
61
+ test "shows an article" do
62
+ article = articles(:published)
63
+
64
+ get api_v1_article_path(article), headers: auth_headers
65
+
66
+ assert_response :success
67
+
68
+ record_openapi_example!(
69
+ name: "published_article",
70
+ summary: "Published article response",
71
+ path_params: { id: article.id }
72
+ )
73
+ end
74
+ end
75
+ ```
76
+
77
+ For create or update actions, you can also record a request body example:
78
+
79
+ ```ruby
80
+ class Api::V1::ArticlesTest < ActionDispatch::IntegrationTest
81
+ openapi_examples path: "/api/v1/articles", method: :post, operation_id: "createArticle"
82
+
83
+ test "creates an article" do
84
+ payload = { title: "Hello" }
85
+
86
+ post api_v1_articles_path, params: payload, as: :json
87
+
88
+ assert_response :created
89
+
90
+ record_openapi_example!(
91
+ name: "create_article",
92
+ summary: "Create article request",
93
+ request_body: payload
94
+ )
95
+ end
96
+ end
97
+ ```
98
+
99
+ Recorded examples are written into the matching OpenAPI operation by:
100
+
101
+ 1. `operationId`, if provided
102
+ 2. otherwise `path + method`
103
+
104
+ Response examples are written under:
105
+
106
+ * `responses.*.content.*.examples`
107
+
108
+ Request examples are written under:
109
+
110
+ * `requestBody.content.*.examples`
111
+
112
+ ## Manual Sync
113
+
114
+ If `auto_write` is disabled, you can write recorded examples manually:
115
+
116
+ ```bash
117
+ bin/rails openapi:examples:write
118
+ ```
119
+
120
+ ## Check examples in CI
121
+
122
+ Enable check mode in your Rails test setup, alongside your existing gem configuration.
123
+
124
+ ```ruby
125
+ MinitestOpenapiExamples.configure do |config|
126
+ config.check_examples = ENV["OPENAPI_EXAMPLES_CHECK"] == "1"
127
+ end
128
+ ```
129
+
130
+ Run the request tests that call `record_openapi_example!`.
131
+
132
+ ```sh
133
+ OPENAPI_EXAMPLES_CHECK=1 bin/rails test test/integration
134
+ ```
135
+
136
+ Each recording compares its sanitized response and any supplied request body with the corresponding examples in the configured spec. A missing or changed example fails the test and identifies the example and endpoint. Update the checked-in example at that key and rerun the test. Check mode takes precedence over `auto_write` and leaves the spec file untouched.
137
+
138
+ Use distinct, stable example names within each operation, status, and media type. The check compares the exact key, including any suffix you explicitly pass in `name:`. Examples that your test run doesn't record are outside the check.
139
+
140
+ ## Configuration
141
+
142
+ The gem supports these configuration options:
143
+
144
+ * `spec_path` - path to the OpenAPI YAML file
145
+ * `sanitizers` - array of lambdas used to sanitize string values
146
+ * `auto_write` - write examples immediately after recording
147
+ * `check_examples` - compare recorded examples against the spec without writing (default: false)
148
+ * `default_content_type` - fallback content type for request and response examples
149
+
150
+ ## Development
151
+
152
+ After checking out the repo, run:
153
+
154
+ ```bash
155
+ bin/setup
156
+ bundle exec rake test
157
+ ```
158
+
159
+ You can also use:
160
+
161
+ ```bash
162
+ bin/console
163
+ ```
164
+
165
+ to experiment with the gem locally.
166
+
167
+ To install this gem onto your local machine, run:
168
+
169
+ ```bash
170
+ bundle exec rake install
171
+ ```
172
+
173
+ ## Roadmap
174
+
175
+ Planned improvements include:
176
+
177
+ * Better YAML output stability
178
+ * Optional request header example support
179
+ * Rails auto-inclusion for `ActionDispatch::IntegrationTest`
180
+ * Improved duplicate example handling across repeated runs
181
+
182
+ ## Contributing
183
+
184
+ Bug reports and pull requests are welcome on GitHub:
185
+
186
+ [https://github.com/galiyafatt2/minitest_openapi_examples](https://github.com/galiyafatt2/minitest_openapi_examples)
187
+
188
+ Please make sure changes include tests where appropriate.
189
+
190
+ ## License
191
+
192
+ This gem is available as open source under the terms of the MIT License.
193
+
194
+ ## Code of Conduct
195
+
196
+ Everyone interacting in the MinitestOpenapiExamples project is expected to follow the code of conduct:
197
+
198
+ [https://github.com/galiyafatt2/minitest_openapi_examples/blob/main/CODE_OF_CONDUCT.md](https://github.com/galiyafatt2/minitest_openapi_examples/blob/main/CODE_OF_CONDUCT.md)
199
+
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Holds settings for recording, writing, and checking examples.
5
+ class Configuration
6
+ attr_accessor :spec_path, :sanitizers, :auto_write, :check_examples, :default_content_type
7
+
8
+ def initialize
9
+ @spec_path = "doc/openapi.yaml"
10
+ @sanitizers = []
11
+ @auto_write = false
12
+ @check_examples = false
13
+ @default_content_type = "application/json"
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Writes the recorded examples to the configured OpenAPI document.
5
+ class ExampleSync
6
+ def initialize(
7
+ registry: MinitestOpenapiExamples.registry,
8
+ document: OpenapiDocument.new
9
+ )
10
+ @registry = registry
11
+ @document = document
12
+ @writer = ExampleWriter.new(document: document)
13
+ end
14
+
15
+ def call
16
+ registry.all.each do |example|
17
+ writer.call(example)
18
+ end
19
+
20
+ document.write!
21
+ registry.clear
22
+ end
23
+
24
+ private
25
+
26
+ attr_reader :registry, :document, :writer
27
+ end
28
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Writes or checks the examples for a recorded request and response.
5
+ class ExampleWriter
6
+ def initialize(document:)
7
+ @document = document
8
+ @operation_finder = OperationFinder.new(document: document)
9
+ end
10
+
11
+ def call(example, check: false)
12
+ operation = operation_finder.call(example)
13
+ raise Error, "OpenAPI operation not found for #{example.http_method.upcase} #{example.path}" unless operation
14
+
15
+ write_response_example(operation, example, check: check)
16
+ write_request_example(operation, example, check: check)
17
+ end
18
+
19
+ private
20
+
21
+ attr_reader :document, :operation_finder
22
+
23
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
24
+ def write_response_example(operation, example, check:)
25
+ response_node = response_node_for(operation, example.response_code)
26
+ content_type = example.response_content_type || MinitestOpenapiExamples.configuration.default_content_type
27
+
28
+ content_node = response_node["content"] ||= {}
29
+ media_type_node = content_node[content_type] ||= {}
30
+ examples_node = media_type_node["examples"] ||= {}
31
+
32
+ name = (example.name || default_response_example_name(example)).to_s
33
+ payload = build_example_payload(summary: example.summary, value: example.response_body)
34
+ sync_example(examples_node, name, payload, check: check) do
35
+ endpoint = "#{example.http_method.upcase} #{example.path}"
36
+ "response example #{name.inspect} for #{endpoint} (#{example.response_code}, #{content_type})"
37
+ end
38
+ end
39
+ # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
40
+
41
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
42
+ def write_request_example(operation, example, check:)
43
+ return if example.request_body.nil?
44
+
45
+ request_body_node = operation["requestBody"] ||= {}
46
+ content_node = request_body_node["content"] ||= {}
47
+
48
+ content_type = MinitestOpenapiExamples.configuration.default_content_type
49
+ media_type_node = content_node[content_type] ||= {}
50
+ examples_node = media_type_node["examples"] ||= {}
51
+
52
+ name = (example.name || default_request_example_name(example)).to_s
53
+ payload = build_example_payload(summary: example.summary, value: example.request_body)
54
+ sync_example(examples_node, name, payload, check: check) do
55
+ "request example #{name.inspect} for #{example.http_method.upcase} #{example.path} (#{content_type})"
56
+ end
57
+ end
58
+ # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
59
+
60
+ def response_node_for(operation, response_code)
61
+ responses = operation["responses"] ||= {}
62
+ responses[response_code] ||= { "description" => "Recorded response" }
63
+ end
64
+
65
+ def build_example_payload(summary:, value:)
66
+ payload = { "value" => value }
67
+ payload["summary"] = summary if summary
68
+ payload
69
+ end
70
+
71
+ def sync_example(examples_node, name, payload, check:)
72
+ if check
73
+ return if examples_node[name] == payload
74
+
75
+ raise Error, "OpenAPI drift in #{yield}. Update the example in #{document.path}."
76
+ end
77
+
78
+ examples_node[next_example_name(examples_node, name)] = payload
79
+ end
80
+
81
+ def next_example_name(examples_node, base_name)
82
+ return base_name unless examples_node.key?(base_name)
83
+
84
+ suffix = 2
85
+
86
+ loop do
87
+ candidate_name = "#{base_name}_#{suffix}"
88
+ return candidate_name unless examples_node.key?(candidate_name)
89
+
90
+ suffix += 1
91
+ end
92
+ end
93
+
94
+ def default_response_example_name(example)
95
+ case example.response_code
96
+ when "200" then "success"
97
+ when "201" then "created"
98
+ when "204" then "no_content"
99
+ when "401" then "unauthorized"
100
+ when "404" then "not_found"
101
+ when "422" then "validation_error"
102
+ else
103
+ "response_#{example.response_code}"
104
+ end
105
+ end
106
+
107
+ def default_request_example_name(example)
108
+ case example.http_method
109
+ when "post" then "create_request"
110
+ when "patch" then "update_request"
111
+ when "put" then "replace_request"
112
+ else
113
+ "request"
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+
5
+ module MinitestOpenapiExamples
6
+ # Loads and saves the configured OpenAPI YAML document.
7
+ class OpenapiDocument
8
+ attr_reader :path, :data
9
+
10
+ def initialize(path: MinitestOpenapiExamples.configuration.spec_path)
11
+ @path = path
12
+ @data = load_data
13
+ end
14
+
15
+ def write!
16
+ File.write(path, YAML.dump(data))
17
+ end
18
+
19
+ private
20
+
21
+ def load_data
22
+ return {} unless File.exist?(path)
23
+
24
+ YAML.safe_load(File.read(path), aliases: true) || {}
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Finds the OpenAPI operation for a recorded example.
5
+ class OperationFinder
6
+ def initialize(document:)
7
+ @document = document
8
+ end
9
+
10
+ def call(example)
11
+ paths = document.data.fetch("paths", {})
12
+
13
+ if example.operation_id
14
+ operation = find_by_operation_id(paths, example.operation_id)
15
+ return operation if operation
16
+ end
17
+
18
+ find_by_path_and_method(paths, example.path, example.http_method)
19
+ end
20
+
21
+ private
22
+
23
+ attr_reader :document
24
+
25
+ def find_by_operation_id(paths, operation_id)
26
+ paths.each_value do |path_item|
27
+ path_item.each do |http_method, operation|
28
+ next unless http_method.is_a?(String)
29
+ next unless operation.is_a?(Hash)
30
+ next unless operation["operationId"] == operation_id
31
+
32
+ return operation
33
+ end
34
+ end
35
+
36
+ nil
37
+ end
38
+
39
+ def find_by_path_and_method(paths, path, http_method)
40
+ path_item = paths[path]
41
+ return unless path_item.is_a?(Hash)
42
+
43
+ path_item[http_method.to_s]
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module MinitestOpenapiExamples
6
+ # Registers the gem's Rake tasks with Rails.
7
+ class Railtie < Rails::Railtie
8
+ rake_tasks do
9
+ load File.expand_path("tasks/minitest_openapi_examples_tasks.rake", __dir__)
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Stores request and response data for one OpenAPI example.
5
+ class RecordedExample
6
+ attr_reader :path,
7
+ :http_method,
8
+ :operation_id,
9
+ :name,
10
+ :summary,
11
+ :path_params,
12
+ :query_params,
13
+ :request_body,
14
+ :response_status,
15
+ :response_content_type,
16
+ :response_body
17
+
18
+ # rubocop:disable Metrics/MethodLength, Metrics/ParameterLists
19
+ def initialize(
20
+ path:,
21
+ http_method:,
22
+ response_status:, response_content_type:, response_body:, operation_id: nil,
23
+ name: nil,
24
+ summary: nil,
25
+ path_params: {},
26
+ query_params: {},
27
+ request_body: nil
28
+ )
29
+ @path = path
30
+ @http_method = http_method.to_s
31
+ @operation_id = operation_id
32
+ @name = name
33
+ @summary = summary
34
+ @path_params = path_params || {}
35
+ @query_params = query_params || {}
36
+ @request_body = request_body
37
+ @response_status = response_status
38
+ @response_content_type = response_content_type
39
+ @response_body = response_body
40
+ end
41
+ # rubocop:enable Metrics/MethodLength, Metrics/ParameterLists
42
+
43
+ def response_code
44
+ response_status.to_s
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Applies the configured sanitizers to recorded example data.
5
+ class Redactor
6
+ def initialize(sanitizers: MinitestOpenapiExamples.configuration.sanitizers)
7
+ @sanitizers = Array(sanitizers)
8
+ end
9
+
10
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
11
+ def call(value)
12
+ case value
13
+ when RecordedExample
14
+ RecordedExample.new(
15
+ path: value.path,
16
+ http_method: value.http_method,
17
+ operation_id: value.operation_id,
18
+ name: value.name,
19
+ summary: sanitize_string_or_value(value.summary),
20
+ path_params: call(value.path_params),
21
+ query_params: call(value.query_params),
22
+ request_body: call(value.request_body),
23
+ response_status: value.response_status,
24
+ response_content_type: value.response_content_type,
25
+ response_body: call(value.response_body)
26
+ )
27
+ when Hash
28
+ value.to_h do |key, nested_value|
29
+ [key, call(nested_value)]
30
+ end
31
+ when Array
32
+ value.map { |nested_value| call(nested_value) }
33
+ when String
34
+ sanitize_string(value)
35
+ else
36
+ value
37
+ end
38
+ end
39
+ # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
40
+
41
+ private
42
+
43
+ attr_reader :sanitizers
44
+
45
+ def sanitize_string_or_value(value)
46
+ return value unless value.is_a?(String)
47
+
48
+ sanitize_string(value)
49
+ end
50
+
51
+ def sanitize_string(value)
52
+ sanitizers.reduce(value) do |current_value, sanitizer|
53
+ sanitizer.call(current_value)
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Collects recorded examples before they are written.
5
+ class Registry
6
+ def initialize
7
+ @examples = []
8
+ end
9
+
10
+ def add(example)
11
+ examples << example
12
+ end
13
+
14
+ def all
15
+ examples.dup
16
+ end
17
+
18
+ def clear
19
+ examples.clear
20
+ end
21
+
22
+ private
23
+
24
+ attr_reader :examples
25
+ end
26
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :openapi do
4
+ namespace :examples do
5
+ desc "Write recorded Minitest OpenAPI examples into the configured spec file"
6
+ task write: :environment do
7
+ MinitestOpenapiExamples::ExampleSync.new.call
8
+ puts "Updated OpenAPI examples in #{MinitestOpenapiExamples.configuration.spec_path}"
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ # Records examples from Rails integration tests.
5
+ module TestHelper
6
+ def self.included(base)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ # Declares the OpenAPI operation exercised by a test class.
11
+ module ClassMethods
12
+ def openapi_examples(path:, method:, operation_id: nil)
13
+ @openapi_examples_metadata = {
14
+ path: path,
15
+ http_method: method.to_s,
16
+ operation_id: operation_id
17
+ }
18
+ end
19
+
20
+ def openapi_examples_metadata
21
+ if instance_variable_defined?(:@openapi_examples_metadata)
22
+ @openapi_examples_metadata
23
+ elsif superclass.respond_to?(:openapi_examples_metadata)
24
+ superclass.openapi_examples_metadata
25
+ end
26
+ end
27
+ end
28
+
29
+ # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
30
+ def record_openapi_example!(
31
+ name: nil,
32
+ summary: nil,
33
+ path_params: {},
34
+ query_params: {},
35
+ request_body: nil
36
+ )
37
+ metadata = self.class.openapi_examples_metadata
38
+ raise MinitestOpenapiExamples::Error, "Missing openapi_examples metadata" unless metadata
39
+
40
+ example = RecordedExample.new(
41
+ path: metadata.fetch(:path),
42
+ http_method: metadata.fetch(:http_method),
43
+ operation_id: metadata[:operation_id],
44
+ name: name,
45
+ summary: summary,
46
+ path_params: path_params,
47
+ query_params: query_params,
48
+ request_body: request_body,
49
+ response_status: response.status,
50
+ response_content_type: response.media_type || MinitestOpenapiExamples.configuration.default_content_type,
51
+ response_body: parsed_response_body
52
+ )
53
+
54
+ sanitized_example = MinitestOpenapiExamples::Redactor.new.call(example)
55
+
56
+ configuration = MinitestOpenapiExamples.configuration
57
+ if configuration.check_examples
58
+ document = OpenapiDocument.new
59
+ ExampleWriter.new(document: document).call(sanitized_example, check: true)
60
+ else
61
+ MinitestOpenapiExamples.registry.add(sanitized_example)
62
+ ExampleSync.new.call if configuration.auto_write
63
+ end
64
+
65
+ sanitized_example
66
+ end
67
+ # rubocop:enable Metrics/AbcSize, Metrics/MethodLength
68
+
69
+ private
70
+
71
+ def parsed_response_body
72
+ return response.parsed_body if response.respond_to?(:parsed_body)
73
+
74
+ response.body
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MinitestOpenapiExamples
4
+ VERSION = "0.2.0"
5
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "minitest_openapi_examples/version"
4
+ require_relative "minitest_openapi_examples/configuration"
5
+ require_relative "minitest_openapi_examples/recorded_example"
6
+ require_relative "minitest_openapi_examples/registry"
7
+ require_relative "minitest_openapi_examples/redactor"
8
+ require_relative "minitest_openapi_examples/test_helper"
9
+ require_relative "minitest_openapi_examples/openapi_document"
10
+ require_relative "minitest_openapi_examples/operation_finder"
11
+ require_relative "minitest_openapi_examples/example_writer"
12
+ require_relative "minitest_openapi_examples/example_sync"
13
+
14
+ require_relative "minitest_openapi_examples/railtie" if defined?(Rails::Railtie)
15
+
16
+ # Records Rails integration test examples for OpenAPI documentation.
17
+ module MinitestOpenapiExamples
18
+ class Error < StandardError; end
19
+
20
+ class << self
21
+ def configuration
22
+ @configuration ||= Configuration.new
23
+ end
24
+
25
+ def configure
26
+ yield(configuration)
27
+ end
28
+
29
+ def reset_configuration!
30
+ @configuration = Configuration.new
31
+ end
32
+
33
+ def registry
34
+ @registry ||= Registry.new
35
+ end
36
+
37
+ def reset_registry!
38
+ @registry = Registry.new
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/minitest_openapi_examples/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "minitest_openapi_examples"
7
+ spec.version = MinitestOpenapiExamples::VERSION
8
+ spec.authors = ["Galiia Fattakhova"]
9
+ spec.email = ["elizabeth.mor324@gmail.com"]
10
+
11
+ spec.summary = "Record OpenAPI examples from Rails Minitest request tests"
12
+ spec.description = "Captures request and response examples from Rails Minitest integration tests, " \
13
+ "redacts unstable values, and writes the examples into an existing OpenAPI spec."
14
+ spec.homepage = "https://github.com/galiyafatt2/minitest_openapi_examples"
15
+ spec.license = "MIT"
16
+ spec.required_ruby_version = ">= 3.1.0"
17
+
18
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/galiyafatt2/minitest_openapi_examples"
22
+ spec.metadata["changelog_uri"] = "https://github.com/galiyafatt2/minitest_openapi_examples/blob/main/CHANGELOG.md"
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(__dir__) do
27
+ `git ls-files -z`.split("\x0").reject do |f|
28
+ (File.expand_path(f) == __FILE__) ||
29
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
30
+ end
31
+ end
32
+ spec.bindir = "exe"
33
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
34
+ spec.require_paths = ["lib"]
35
+
36
+ spec.add_dependency "railties", ">= 6.1"
37
+
38
+ # Uncomment to register a new dependency of your gem
39
+ # spec.add_dependency "example-gem", "~> 1.0"
40
+
41
+ # For more information and examples about making a new gem, check out our
42
+ # guide at: https://bundler.io/guides/creating_gem.html
43
+ end
@@ -0,0 +1,4 @@
1
+ module MinitestOpenapiExamples
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: minitest_openapi_examples
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Galiia Fattakhova
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-11-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: railties
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.1'
27
+ description: Captures request and response examples from Rails Minitest integration
28
+ tests, redacts unstable values, and writes the examples into an existing OpenAPI
29
+ spec.
30
+ email:
31
+ - elizabeth.mor324@gmail.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - ".idea/.gitignore"
37
+ - ".idea/minitest_openapi_examples.iml"
38
+ - ".idea/modules.xml"
39
+ - ".idea/vcs.xml"
40
+ - ".rubocop.yml"
41
+ - CHANGELOG.md
42
+ - CODE_OF_CONDUCT.md
43
+ - LICENSE.txt
44
+ - README.md
45
+ - Rakefile
46
+ - lib/minitest_openapi_examples.rb
47
+ - lib/minitest_openapi_examples/configuration.rb
48
+ - lib/minitest_openapi_examples/example_sync.rb
49
+ - lib/minitest_openapi_examples/example_writer.rb
50
+ - lib/minitest_openapi_examples/openapi_document.rb
51
+ - lib/minitest_openapi_examples/operation_finder.rb
52
+ - lib/minitest_openapi_examples/railtie.rb
53
+ - lib/minitest_openapi_examples/recorded_example.rb
54
+ - lib/minitest_openapi_examples/redactor.rb
55
+ - lib/minitest_openapi_examples/registry.rb
56
+ - lib/minitest_openapi_examples/tasks/minitest_openapi_examples_tasks.rake
57
+ - lib/minitest_openapi_examples/test_helper.rb
58
+ - lib/minitest_openapi_examples/version.rb
59
+ - minitest_openapi_examples.gemspec
60
+ - sig/minitest_openapi_examples.rbs
61
+ homepage: https://github.com/galiyafatt2/minitest_openapi_examples
62
+ licenses:
63
+ - MIT
64
+ metadata:
65
+ allowed_push_host: https://rubygems.org
66
+ homepage_uri: https://github.com/galiyafatt2/minitest_openapi_examples
67
+ source_code_uri: https://github.com/galiyafatt2/minitest_openapi_examples
68
+ changelog_uri: https://github.com/galiyafatt2/minitest_openapi_examples/blob/main/CHANGELOG.md
69
+ post_install_message:
70
+ rdoc_options: []
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: 3.1.0
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubygems_version: 3.4.19
85
+ signing_key:
86
+ specification_version: 4
87
+ summary: Record OpenAPI examples from Rails Minitest request tests
88
+ test_files: []