On this page
The short answerWhy Ruby documentation examples breakClassify the block and its contextStart with syntax and warningsMake gem dependencies explicitTurn result comments into assertionsCheck YARD examples outside the generated docsExtract and check Markdown fencesRun the checks in CITriage failures before filing a bugWhere DocsAlive fitsPasteable checklistThe sources we checkedFAQThe short answer
Test Ruby documentation examples in a clean environment with the Ruby and gem versions the page promises: syntax-check extracted code, run complete scripts, and turn important expected results into assertions. Treat interactive sessions, configuration and fragments according to their intended context. Record what ran, what was skipped and what setup the test supplied so a failure can be separated from a genuine documentation bug.
Run checks when docs or public APIs change, against the release artifact when practical, and on a schedule for dependency drift. A syntax check is a useful first filter; it does not load dependencies or establish that the documented result is correct. For the wider process, see documentation testing and SDK documentation testing.
DocsAlive recognizes ruby and rb fences but does not compile, lint or run them. It reports them as skipped with reason not executable (ruby) and category not-executable. Use your own Ruby checks in CI; the service can still check supported blocks elsewhere on the same page.
Why Ruby documentation examples break
Ruby examples often look small because their environment does work that is not visible in the snippet. A maintainer’s console may already have loaded a library, installed a gem or initialized an application. A reader copying the same lines into a fresh process can encounter a missing constant or method before reaching the behavior the page intends to teach.
Missing require lines are a frequent cause. The name used to install a gem and the path used in require need not be identical. Document both when they differ, and test the exact instructions in a clean environment. A successful require on a maintainer’s machine does not establish that the page named the correct dependency or version.
Gem APIs change. A method may be renamed, removed or accept different arguments in a later release. Ruby itself also changes: syntax and library features can depend on the interpreter version, and keyword-argument behavior can differ across versions. A page that says only “install the gem” leaves readers and maintainers uncertain about which combination an example promises to support.
Rails and IRB state create further dependencies. A Rails console has application setup and constants that a plain Ruby process may not have. An IRB session can retain variables and loaded libraries from earlier commands. Those are legitimate environments when the page says so, but an isolated script test will not reproduce them automatically. Conversely, a test that silently supplies their state may conceal a missing prerequisite.
Comments such as #=> 4 are also promises. They are easy to copy from an interactive session and easy to forget when behavior changes. A script can exit successfully while a result comment becomes stale. Check stable values with assertions and decide how variable output should be described.
A rendered page, generated reference or passing site build does not by itself prove that code ran. Treat source examples as a maintained interface: identify the environment, execute the path and review the result.
Classify the block and its context
Before automating, make an inventory of what each block asks a reader to do. The same-looking line can be a complete script, one step in a console session or a fragment intended for an existing application.
| Block | Reader’s intended use | Appropriate check |
|---|---|---|
| Complete script | Save and run the file | Syntax-check, execute in a clean directory and verify the result |
| IRB-style session | Enter commands in order and inspect responses | Reproduce the session’s state and compare meaningful results |
| Gemfile or configuration | Save settings for Bundler or an application | Validate it in a representative project with the stated dependencies |
| Fragment | Insert code into an existing file or context | Mark it clearly and check it in a representative wrapper or test |
| Output | Compare with a command’s result | Check stable values and identify fields that can vary |
A fragment may parse as a Ruby program while still requiring a variable, method or framework context. That makes a syntax pass useful but limited. A session may include prompts and displayed values that are not source code to save verbatim. Give readers enough instructions to distinguish input from output, and use a session-aware check or a maintained script that reproduces the commands in order.
Keep separate pages separate unless the docs explicitly connect them. Within a tutorial, preserve the order and state the reader is told to create. A later block that depends on a previous assignment should not be judged as a standalone script without that context. Quickstart testing covers testing a complete sequence.
Start with syntax and warnings
Ruby’s -c option checks syntax without executing the program. For a valid file it prints Syntax OK and exits successfully; syntax errors produce a non-zero exit. It does not load a required gem, call an API or evaluate a result. The Ruby command-line options describe the switch.
Save this complete example as hello.rb:
require "json"
message = JSON.generate("status" => "ready")
puts message
Check its syntax, then run it:
ruby -c hello.rb
ruby -w hello.rb
The second command executes the program with warnings enabled. Review warnings in context: they may point to documentation that needs an update, or to a dependency and environment that need investigation. A warning is not automatically proof that a reader will encounter the same problem under the documented setup.
The example uses json, a default gem shipped with Ruby. It prints a JSON object containing the status value. It does not need an external service or a credential. Use similarly self-contained examples when the behavior being taught does not require a network call.
Syntax-check each extracted Ruby block, including marked fragments, when it is meaningful to parse the block as written. Some deliberate fragments are syntactically incomplete; record those as exceptions rather than rewriting the page to satisfy an unrelated isolated check. A fragment that parses can still fail at runtime because its required context is absent.
Run complete scripts in a clean directory
A clean working directory helps expose accidental dependencies on local files. Use a fresh process and the Ruby version stated by the page. For example, after saving hello.rb in the current directory:
sample_dir=$(mktemp -d)
cp hello.rb "$sample_dir/hello.rb"
cd "$sample_dir"
ruby hello.rb
This isolates the working directory, not the entire machine. Installed gems, environment variables and Ruby configuration can still affect the run. For stronger isolation, use a fresh CI environment or container and document the gems installed there. Do not put real credentials into a copied example or its logs.
Compare the execution with the page’s promise. A zero exit status establishes that the process succeeded, not that the displayed output or side effects are correct. Check fixed values exactly when the page presents them as exact. For generated values, explain which properties matter and verify those properties.
Make gem dependencies explicit
A reliable example identifies the gem to install, the version or supported range, and the require path. It also says whether a command belongs in the shell, a Gemfile, a script or a Rails console. Test the documented installation command as a reader would, rather than relying on a gem that happens to be installed globally.
For a multi-file project, a Gemfile and lockfile can make the resolved dependency set reproducible. Record whether the test uses a local checkout, a built gem or the published gem. Those checks answer different questions: code in the checkout may work even if the packaged artifact is missing a file or the published version does not contain the documented method.
For a single-file example, bundler/inline can declare dependencies in the script. The following block is illustrative and will not install: acme_sdk and Acme SDK are fictional. Replace the dependency, version, load path and usage with those of a real gem before using this pattern. The source address shown is the standard RubyGems package source.
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "acme_sdk", "1.2.3"
end
require "acme_sdk"
The single-file Bundler guide explains the pattern. Running an inline declaration can install missing gems, so it is a dependency and network operation, not merely a syntax check. Use a controlled environment and trusted dependency sources.
For examples that need an API key, explain the variable and the reader’s setup without embedding a real value. If a fictional example uses ACME_API_KEY, label the SDK and service as fictional. An authorized integration test can use a test credential in a separate environment, but a local syntax pass does not establish that authentication or a remote request works. See credentials in documentation examples.
Default and bundled gems
Ruby distributes some libraries as default gems and others as bundled gems. That distinction matters when Bundler controls the dependencies available to a script. The RubyGems guide describes the two categories.
json is a default gem and is suitable for the self-contained example above. minitest is a bundled gem: when using Bundler, declare gem "minitest" in the Gemfile. As listed by Standard Gems, Ruby 3.4 ships minitest 5.25.4 and Ruby 4.0 ships 6.0.0. State or lock the version when a test suite depends on version-specific behavior, and test the combinations the documentation supports.
Turn result comments into assertions
A #=> comment is convenient for a reader, but Ruby does not compare it with the expression’s value. Mirror the important claim in a test. This complete example uses json and the bundled minitest available with Ruby 3.4. Save it as test_docs.rb and run it with ruby test_docs.rb:
require "json"
require "minitest/autorun"
class DocumentationExampleTest < Minitest::Test
def test_documented_result
data = JSON.parse('{"count":3}')
assert_equal 3, data.fetch("count")
end
end
If the same test runs under Bundler, include gem "minitest" in the project’s Gemfile and install the bundle first. The minitest documentation describes the test class and assertions.
Keep the test connected to the documented example. A reference to the page and section in the test file or test name makes it easier to review both when an API changes. If the documentation shows several steps, reproduce the sequence instead of asserting only the final value from a separately constructed fixture.
Do not assert incidental output merely because it was printed once. Timestamps, random values and remote response ordering can vary. If a result is representative, say so in the page and test the properties a reader can rely on. If a result comment claims an exact answer for fixed input, assert that answer.
A failing assertion also needs interpretation. The code may have changed correctly while the comment is stale, or the implementation may have regressed. Compare the documented version, the installed version and the intended contract before deciding which artifact to update.
Check YARD examples outside the generated docs
YARD’s @example tag documents a snippet; YARD does not run it. Generating reference pages can therefore succeed while a method name, argument or expected result in an example is stale. The YARD tag documentation describes the tag and its optional title.
Mirror consequential YARD examples into tests or extract them into a suitable test harness. Preserve the setup a reader has at that point: an example for an instance method may assume an object constructed in surrounding documentation. Make that setup visible in the test and check that it is also explained to readers.
Review the generated page as well as the source. Execution can verify code behavior, while a page review can find misleading placement, missing indentation or a context that no longer appears near the example. API reference documentation testing covers the wider reference workflow.
Extract and check Markdown fences
The following Python 3 script extracts simple, unindented fences labeled ruby or rb. It writes each block to a temporary .rb file and runs ruby -c on every extracted block. With --run, it also executes syntax-valid blocks that do not contain a # fragment marker. It reports a summary and exits non-zero for syntax failures, execution failures or unclosed matching fences.
Save it as check_ruby_docs.py. It requires Python 3.12 and Ruby. Only use --run on trusted documentation: extracted code runs with the permissions and environment of the CI job.
import re
import subprocess
import sys
import tempfile
from pathlib import Path
OPEN = re.compile(r"^(`{3,}|~{3,})\s*(ruby|rb)\s*$", re.I)
FRAGMENT = re.compile(r"^\s*#\s*fragment\b", re.I)
def blocks(path):
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
i = 0
while i < len(lines):
match = OPEN.match(lines[i].rstrip("\r\n"))
if not match:
i += 1
continue
fence = match.group(1)
start = i + 1
i += 1
body = []
while i < len(lines):
line = lines[i].rstrip("\r\n")
if re.fullmatch(re.escape(fence[0]) + r"{" + str(len(fence)) + r",}\s*", line):
yield start, "".join(body)
i += 1
break
body.append(lines[i])
i += 1
else:
raise ValueError(f"{path}:{start}: unclosed fence")
def invoke(command):
return subprocess.run(
command,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False,
)
def main():
args = sys.argv[1:]
run_examples = "--run" in args
files = [arg for arg in args if arg != "--run"]
if not files:
print("Usage: python check_ruby_docs.py [--run] FILE.md [FILE.md ...]")
return 2
checked = executed = skipped = failed = 0
with tempfile.TemporaryDirectory(prefix="ruby-docs-") as temp:
root = Path(temp)
number = 0
for argument in files:
path = Path(argument)
try:
for line, code in blocks(path):
number += 1
label = f"{path}:{line}"
sample = root / f"example{number}.rb"
sample.write_text(code, encoding="utf-8")
syntax = invoke(["ruby", "-c", str(sample)])
checked += 1
if syntax.returncode:
failed += 1
print(f"FAIL syntax {label}\n{syntax.stdout}")
continue
print(f"PASS syntax {label}: {syntax.stdout.strip()}")
fragment = any(
FRAGMENT.match(part) for part in code.splitlines()
)
if not run_examples or fragment:
skipped += 1
print(f"SKIP execution {label}")
continue
result = invoke(["ruby", str(sample)])
if result.returncode:
failed += 1
print(f"FAIL execution {label}\n{result.stdout}")
else:
executed += 1
print(f"PASS execution {label}\n{result.stdout}")
except (OSError, ValueError) as error:
failed += 1
print(f"FAIL {error}")
print(
f"Summary: {checked} syntax checked, {executed} executed, "
f"{skipped} execution skipped, {failed} failed"
)
return 1 if failed else 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except FileNotFoundError as error:
print(f"Required tool not found: {error}")
raise SystemExit(1)
Run syntax checks on named files:
python3 check_ruby_docs.py README.md docs/guide-1.md
Add --run only after classifying the selected blocks and arranging their required dependencies:
python3 check_ruby_docs.py --run README.md docs/guide-1.md
The script checks fragments for syntax before deciding whether to skip their execution. A deliberately incomplete fragment can therefore fail ruby -c; either provide a representative syntax-check wrapper or maintain an explicit exception outside this basic script. Do not mistake a skipped execution for a successful run.
This is a small starting point, not a complete Markdown or MDX parser. It accepts unindented fences with a language label alone, runs blocks independently and does not compare #=> comments. It does not reconstruct an IRB session, Rails environment or page sequence. Its temporary files are separate, but processes inherit the job environment and working directory. Adapt isolation and parsing to the repository, and review the list of selected files.
A summary with zero blocks is not meaningful coverage. Check the inventory and, in a production job, enforce an expected count or another coverage rule appropriate to the repository. Use maintained tests for behavior and output in addition to this extraction check.
Run the checks in CI
This GitHub Actions outline selects Ruby 3.4, installs the project bundle and runs the extraction script plus a maintained test file. Commit the script and the referenced files, and adjust paths to match the repository.
name: Check Ruby documentation
on:
push:
pull_request:
jobs:
ruby-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4'
bundler-cache: true
- name: Check Markdown examples
run: bundle exec python3 check_ruby_docs.py --run README.md docs/guide-1.md
- name: Run documentation assertions
run: bundle exec ruby test/test_docs.rb
The outline assumes a Gemfile, the listed Markdown files and test/test_docs.rb exist. Declare minitest in the Gemfile if that test uses it. bundle exec supplies the bundle environment to Ruby processes launched by the extractor; ensure that every executable selected by --run is appropriate for that environment.
The RubyGems CI guide explains that bundler-cache: true installs and caches the bundle. With a Gemfile.lock, setup uses deployment mode, so an out-of-date lockfile makes the job fail. That failure can identify a dependency-management problem rather than a code-example failure. The setup action documentation describes its inputs.
Use separate explicit jobs for other Ruby versions the product promises to support. Run relevant checks on pull requests, test the release artifact before publication when it is a release gate, and schedule checks for dependency drift. A post-release check against the published gem is useful evidence of the reader’s installation path, although it cannot block a release that has already shipped. See GitHub Actions documentation testing.
Record Ruby maintenance status
As read on November 10, 2026, the Ruby maintenance branches page lists Ruby 4.0 and 3.4 in normal maintenance. Ruby 3.3 is in security maintenance, with an expected end of life of March 31, 2027; Ruby 3.2 reached end of life on April 1, 2026.
Maintenance status does not determine whether a particular gem supports a Ruby version. State the minimum and tested Ruby versions alongside the gem version, and keep the support promise distinct from the versions selected for CI. Revisit both as the interpreter and dependencies change.
Triage failures before filing a bug
Keep the source location, Ruby version, resolved gem versions, command and error output with each result. That context helps a reviewer reproduce the problem and decide whether it belongs in the docs, code, test setup or external environment.
| Finding | Likely interpretation | Next action |
|---|---|---|
| Syntax error in a complete script | Possible documentation bug or unsupported Ruby version | Reproduce with the stated version and correct the sample or requirement |
| Missing constant or load error | Missing require, missing gem or mismatched load path |
Follow the documented install and require steps in a clean environment |
| Removed method or changed keyword arguments | Possible API or Ruby version drift | Compare the installed versions with the page’s promise |
| Fragment fails when run alone | Missing intended context or classification | Mark the fragment and check it in a representative wrapper |
#=> value differs |
Possible stale output or changed behavior | Assert the stable result and inspect the intended contract |
| Network or credential failure | External dependency blocked the path | Review setup and retry in an authorized environment |
| Warning from a dependency | Maintenance signal that needs context | Identify its source and decide whether the docs or dependency need action |
A missing fixture can be a legitimate prerequisite or an omission in the page. Ask whether the reader was told how to obtain it. Similarly, a test harness that loads Rails or creates a variable can make a fragment pass while hiding a missing instruction. Record that setup and compare it with the published path.
For a result that varies, distinguish the documented contract from incidental output. A changed identifier or time may be expected; a renamed method or wrong fixed result may stop readers. Avoid treating every raw failure as a documentation defect, but do not discard repeated failures without understanding their cause.
Where DocsAlive fits
Label Ruby fences ruby or rb so a scan reports them explicitly. Both labels map to Ruby, and those blocks are skipped with reason not executable (ruby) and report category not-executable. They have no Ruby pass or fail result from the service. Run your own syntax, execution and assertion checks in CI.
The service can check supported blocks on the same page, including shell commands, HTTP requests, JSON or TOML, Python and JavaScript. It processes blocks in page order in a fresh container for each page and reports the skipped Ruby blocks so the coverage gap remains visible. The default runner has no Ruby; a shell block invoking ruby, gem or bundle there would likely be reported as a missing tool. Credential-gated blocks are classified rather than run with real keys. See supported frameworks and languages and finding categories.
Use the scan alongside your Ruby job rather than reading a skip as a pass. Review which parts of a page each check actually covered, including setup and output. A person should still assess whether the instructions are clear and whether a reader can follow the complete path.
Pasteable checklist
- [ ] Inventory Ruby scripts, interactive sessions, configuration and fragments.
- [ ] Label Ruby fences
rubyorrband identify the intended context. - [ ] State the minimum and tested Ruby versions and the relevant gem versions.
- [ ] Document installation and
requirepaths, including any difference between them. - [ ] Run
ruby -con extracted blocks and account for deliberately incomplete fragments. - [ ] Run complete scripts in a clean environment and review warnings.
- [ ] Reproduce session state and tutorial steps in the documented order.
- [ ] Turn important
#=>claims into assertions. - [ ] Mirror consequential YARD examples into tests.
- [ ] Declare bundled test gems in the Gemfile when using Bundler.
- [ ] Test the release artifact or published gem when it is the reader’s install path.
- [ ] Record credentials, fixtures, external failures and skipped execution.
- [ ] Run checks on relevant changes and releases, and schedule drift checks.
The sources we checked
These sources were read on November 10, 2026.
| Source | What it covers |
|---|---|
| Ruby command-line options | Syntax checking, warning levels and execution options |
| YARD tags | The @example documentation tag |
| minitest | Test classes and assertions |
| Bundler in a single-file script | Inline dependency declarations |
| Bundler in CI | Setup, caching and lockfile behavior |
| Default and bundled gems | Ruby’s gem distribution categories |
| Standard Gems: minitest | Bundled status and versions shipped with Ruby |
| Ruby maintenance branches | Branch maintenance status and expected dates |
| Setup Ruby action | Ruby selection and Bundler caching in GitHub Actions |
FAQ
Does ruby -c run a documentation example?
No. It checks syntax without executing the program. A valid file prints Syntax OK, but the check does not establish that dependencies load, methods exist or the result matches the page.
How should I test an IRB-style session?
Reproduce its commands in order with the documented loaded libraries and state, then compare meaningful results. Prompts and displayed output are not necessarily a standalone Ruby script.
How can I keep result comments accurate?
Mirror important fixed results in assertions, such as an assert_equal check in a minitest test. For variable results, explain and test the properties a reader can rely on.
Does YARD execute examples in reference comments?
No. The @example tag documents a snippet. Mirror or extract consequential examples into tests and inspect the generated page separately.
Why declare minitest in a Gemfile?
Minitest is a bundled gem. When Bundler controls the project dependencies, declare gem "minitest" in the Gemfile so the test can use it. Record the version when your test depends on version-specific behavior.
Can DocsAlive run Ruby examples?
It recognizes ruby and rb fences but skips them as not executable, with category not-executable. Use your own Ruby checks in CI; supported blocks elsewhere on the page can still be checked.




