Architecture rules for Ruby, enforced in your tests.
Keep dependency boundaries explicit, catch cycles, enforce conventions, measure code quality, and generate architecture diagrams—with readable rules in RSpec, Minitest, or plain Ruby.
ArchUnit.project_files.in_folder('app/api/**')
.should_not.depend_on_files.in_folder('app/database/**')
.because('Keep persistence behind the service boundary')ArchUnitRuby analyzes source with Prism without booting your application. It is the Ruby member of the ArchUnitEverything family, inspired by—but not affiliated with—ArchUnit.
Quickstart · Capabilities · User guide · API contract · Documentation site · Example project · Limitations
| Version | Capabilities |
|---|---|
1.0 |
Fluent file/layer/slice rules, cycles and naming, metrics, graph/diagram exports, RSpec/Minitest integrations, opt-in constant-file analysis |
1.1 |
Everything in 1.0, plus CLI, analysis diagnostics, accepted-debt baselines, architecture presets, Rails helper imports, caller-owned source exclusions, and further extraction fixes |
This guide and its installation example target the 1.1 series. Check
RubyGems for published versions; the documentation site
follows main and can be ahead of the registry during release preparation.
Installing 1.0.0 does not provide the CLI or other 1.1 additions. See the
changelog and 1.x compatibility contract before upgrading.
Ruby 3.3+ is required. Add ArchUnitRuby to your test dependencies:
# Gemfile
group :test do
gem 'archunit', '~> 1.1.0'
gem 'rspec' # Omit this line if RSpec is already in your bundle.
endbundle installRSpec and Minitest are optional integrations, not runtime dependencies of the gem.
Already using Minitest? Keep your existing setup and use assert_passes(rule).
For this example, use two ordinary source files:
app/
api/request.rb # class Request; end
database/store.rb # class Store; end
spec/
architecture_spec.rb
Create spec/architecture_spec.rb. Change the folder patterns to match your project.
require 'archunit'
RSpec.describe 'Architecture' do
it 'keeps the API away from the database' do
rule = ArchUnit.project_files.in_folder('app/api/**')
.should_not.depend_on_files.in_folder('app/database/**')
.because('Keep persistence behind the service boundary')
expect(rule).to pass
end
endbundle exec rspec spec/architecture_spec.rbNo special CI service is required: run architecture specifications with your normal tests.
Add this line to app/api/request.rb and rerun the test:
require_relative '../database/store'The test fails with concrete file evidence:
File dependency violation
File 'app/api/request.rb' depends on forbidden file 'app/database/store.rb'.
Remove that dependency in this small fixture to return to green. In an application, refactor the interaction through your intended service boundary instead of merely suppressing the test. In a long-lived process, clear the graph cache after source edits; separate RSpec runs start fresh.
Complete workflows · Watch the recorded demo
| Capability | Public entry point | Details |
|---|---|---|
| File boundaries, external modules, naming, locations, custom predicates | project_files |
File rules |
| Directed dependency cycles | project_files.should.have_no_cycles |
Rule recipes |
| Named-layer allowlists and blocklists | project_layers |
Layer rules |
| Component slices and PlantUML conformance | project_slices |
Slices and diagrams |
| Mermaid, DOT, D2, JSON, CSV, and offline HTML reports | project_graph |
Graph reports |
| Counts, cohesion, coupling, distance, and custom thresholds | metrics |
Metrics |
| Layered, hexagonal, and Rails presets | architecture_preset — 1.1+ |
Preset contract |
Builders are immutable and lazy: assembling a rule does not scan the project. Terminal calls
such as check, measure, snapshot, and exports perform the work.
check returns structured violations; framework integrations turn them into test failures.
| Integration | Assertion |
|---|---|
| RSpec | expect(rule).to pass |
| Minitest | assert_passes(rule) |
| Plain Ruby | ArchUnit.assert_passes(rule) |
A cycle rule:
rule = ArchUnit.project_files.in_path('app/**/*.rb').should.have_no_cycles
ArchUnit.assert_passes(rule)An architecture report:
report = ArchUnit.project_graph.collapse_to_folder_depth(2).titled('Application dependencies')
report.export_as_html('reports/architecture.html')
puts report.to_mermaidA metric threshold:
rule = ArchUnit.metrics.in_path('app/services/**/*.rb')
.count.method_count.should_be_below_or_equal(20)
ArchUnit.assert_passes(rule)See the user guide for layer/slice policies, custom predicates, logging, report queries, and complete examples.
The default :imports mode recognizes supported static require, require_relative,
autoload, and load calls. It does not infer the runtime behavior of Ruby.
For autoloaded code, explicitly add the supported static constant-reference model:
rule = ArchUnit.project_files.in_folder('app/api/**')
.should_not.depend_on_files.in_folder('app/database/**')
options = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants)
violations = rule.check(options)Expanded analysis maps known project constants to definition files and retains evidence. It is still bounded: ambiguous, inherited, or dynamic lookup can remain unresolved. Resolution details · Options and caching
These commands require ArchUnitRuby 1.1 or newer. They are not available in 1.0.0.
bundle exec archunit init
# Review and customize the generated .archunit.rb before running it.
bundle exec archunit check
bundle exec archunit check --format json --dependency-analysis imports_and_constants
bundle exec archunit explainThe CLI composes the same rules as your tests. It reports source/uncertainty diagnostics without
turning unknowns into a semantic-coverage percentage. explain lists configuration; it does not
prove that rules passed.
For gradual adoption, explicitly record reviewed violations:
bundle exec archunit baseline --output .archunit-baseline.json
bundle exec archunit check --baseline .archunit-baseline.jsonEvery rule still runs. New violations and stale entries for fixed debt fail the check.
An accepted result is not a clean passed result. Review baseline changes; do not regenerate
them blindly in CI. Presets compose existing layer rules and retain empty-layer and overlap guards.
Trust boundary: .archunit.rb is executable Ruby, including during explain. For an untrusted
repository, use your own trusted --config file. The analyzer does not automatically execute
target source, Gemfiles/gemspecs, tests, or Rails boot; your own Bundler/configuration code still
has normal Ruby behavior.
CLI contract · Baseline contract · Presets
- Empty subject selections fail by default; they are usually a typo, not a clean architecture.
- Malformed included Ruby raises
SourceParseError. Exclude identified generator templates explicitly; a rule selector does not narrow whole-project source discovery. - Runtime-derived imports, ambiguous constants, inherited lookup, and metaprogramming can stay unresolved. Passing a policy describes the resolved static model—not complete runtime behavior.
- Whole-project exclusions and rule selectors serve different purposes. Source symlinks are skipped; cached graphs require explicit clearing after edits in a long-lived process.
- Full method-call/signature protocols and semantic component selectors are not shipped. The semantic evaluation is a decision record, not feature parity. Dense cycle enumeration can still be expensive.
Full analysis contract · Errors and troubleshooting
The Ruby RAG example is a small layered application with intentional architecture violations. Use it for a hands-on walkthrough; its tests also run against the current checkout in our CI.
The library dogfoods its own architecture. CI checks Ruby 3.3/3.4/4.0 on Linux and Ruby 4.0 on Windows, gates runtime-library coverage at 98% line / 90% branch, validates docs and package installation, and runs security checks. Coverage measures executed test paths, not Ruby semantic completeness or a guarantee that no bugs remain.
Four pinned production-library canaries—Rack, Rake, RSpec Core, and RestClient—exercise passing and deliberately failing policies. A broader 50-repository source audit and the separate Linux performance study provide bounded evidence, not upstream architecture/security judgments or a universal speed claim.
- User guide: recipes, project discovery, exclusions, Ruby analysis, CLI, and migration.
- API contract: exact behavior, options, report formats, and errors.
- Online documentation: getting started, guides,
and searchable source-generated reference; follows
main. - Changelog, contributing, security, support, and release process.
To work on the library:
git clone https://github.com/dragonsec-ai/ArchUnitRuby.git
cd ArchUnitRuby
bundle install
bundle exec rake
bundle exec rake docsMaintained by Tristan Kruse and Lukas Niessen, with our contributors.
Part of the ArchUnitEverything family alongside ArchUnitTS and ArchUnitPython. Questions and feature requests belong in GitHub Issues; report vulnerabilities through SECURITY.md.
MIT license. Download analytics count package fetches, not unique users.
