Rails Audit Skill (thoughtbot Best Practices)
Perform comprehensive Ruby on Rails application audits based on thoughtbot's Ruby Science and Testing Rails best practices, with emphasis on Plain Old Ruby Objects (POROs) over Service Objects.
Audit Scope
The audit can be run in two modes:
- Full Application Audit: Analyze entire Rails application
- Targeted Audit: Analyze specific files or directories
Execution Flow
Step 1: Determine Audit Scope
Ask user or infer from request:
- Full audit: Analyze all of
app/, spec/ or test/, config/, db/, lib/
- Targeted audit: Analyze specified paths only
Step 2: Collect Optional Metrics (SimpleCov + RubyCritic)
Ask the user both questions upfront in a single AskUserQuestion so they can decide once:
- Question: "Before starting the audit, would you like to collect automated metrics?\n\n1. SimpleCov — runs your test suite to capture actual code coverage percentages\n2. RubyCritic — analyzes code complexity, duplication, and smells (does not run tests)\n\nBoth are recommended for the most thorough audit."
- Options: "Yes to both (Recommended)" / "SimpleCov only" / "RubyCritic only" / "Skip both"
Based on the user's choice, spawn the accepted subagents in parallel using the Task tool. Both can run at the same time because SimpleCov modifies the test helper while RubyCritic only reads source files — they don't conflict.
SimpleCov subagent (if accepted):
Read the file agents/simplecov_agent.md and follow all steps described in it. The audit scope is: {{SCOPE from Step 1}}. Return the coverage data in the output format specified in that file.
RubyCritic subagent (if accepted):
Read the file agents/rubycritic_agent.md and follow all steps described in it. The audit scope is: {{SCOPE from Step 1}}. Return the code quality data in the output format specified in that file.
After both agents finish, clean up:
- If SimpleCov ran:
rm -rf coverage/
- If RubyCritic ran:
rm -rf tmp/rubycritic/
Interpreting responses:
COVERAGE_FAILED / RUBYCRITIC_FAILED: no data for that tool — use estimation mode (SimpleCov) or omit the section (RubyCritic). Note the failure reason in the report.
COVERAGE_DATA: parse and keep in context for Steps 4 and 5 (overall coverage, per-directory breakdowns, lowest-coverage files, zero-coverage files).
RUBYCRITIC_DATA: parse and keep in context for Steps 4 and 5 (overall score, per-directory ratings, worst-rated files, top smells, most complex files).
Step 3: Load Reference Materials
Before analyzing, read the relevant reference files:
references/code_smells.md - Code smell patterns to identify
references/testing_guidelines.md - Testing best practices
references/poro_patterns.md - PORO and ActiveModel patterns
references/security_checklist.md - Security vulnerability patterns
references/rails_antipatterns.md - Rails-specific antipatterns (external services, migrations, performance)
Step 4: Analyze Code by Category
Analyze in this order:
Testing Coverage & Quality
- If SimpleCov data was collected in Step 2, use actual coverage percentages instead of estimates
- Cross-reference per-file SimpleCov data: files with 0% coverage = "missing tests"
- Check for missing test files
- Identify untested public methods
- Review test structure (Four Phase Test)
- Check for testing antipatterns
Security Vulnerabilities
- SQL injection risks
- Mass assignment vulnerabilities
- XSS vulnerabilities
- Authentication/authorization issues
- Sensitive data exposure
Models & Database
- Fat model detection
- Missing validations
- N+1 query risks
- Callback complexity
- Law of Demeter violations (voyeuristic models)
- If RubyCritic data was collected, flag models with D/F ratings or high complexity
Controllers
- Fat controller detection
- Business logic in controllers
- Missing strong parameters
- Response handling
- Monolithic controllers (non-RESTful actions, > 7 actions)
- Bloated sessions (storing objects instead of IDs)
- If RubyCritic data was collected, flag controllers with D/F ratings or high complexity
Code Design & Architecture
- Service Objects → recommend PORO refactoring
- Large classes
- Long methods
- Feature envy
- Law of Demeter violations
- Single Responsibility violations
- If RubyCritic data was collected, cross-reference D/F rated files and high-complexity files with manual code review findings
Views & Presenters
- Logic in views (PHPitis)
- Missing partials for DRY
- Helper complexity
- Query logic in views
External Services & Error Handling
- Fire and forget (missing exception handling for HTTP calls)
- Sluggish services (missing timeouts, synchronous calls that should be backgrounded)
- Bare rescue statements
- Silent failures (save without checking return value)
Database & Migrations
- Messy migrations (model references, missing down methods)
- Missing indexes on foreign keys, polymorphic associations, uniqueness validations
- Performance antipatterns (Ruby iteration vs SQL queries)
- Bulk operations without transactions
Step 5: Generate Audit Report
Create RAILS_AUDIT_REPORT.md in project root with structure defined in references/report_template.md.
When SimpleCov coverage data was collected in Step 2, use the SimpleCov variant of the Testing section in the report template. When coverage data is not available, use the estimation variant.
When RubyCritic data was collected in Step 2b, include the Code Quality Metrics section in the report using the RubyCritic variant from the report template. When RubyCritic data is not available, use the not available variant.
Severity Definitions
- Critical: Security vulnerabilities, data loss risks, production-breaking issues
- High: Performance issues, missing tests for critical paths, major code smells
- Medium: Code smells, convention violations, maintainability concerns
- Low: Style issues, minor improvements, suggestions
Key Detection Patterns
Service Object → PORO Refactoring
When you find classes in app/services/:
- Classes named
*Service, *Manager, *Handler
- Classes with only
.call or .perform methods
- Recommend: Rename to domain nouns, include
ActiveModel::Model
Fat Model Detection
Models with:
- More than 200 lines
- More than 15 public methods
- Multiple unrelated responsibilities
- Recommend: Extract to POROs using composition
Fat Controller Detection
Controllers with:
- Actions over 15 lines
- Business logic (not request/response handling)
- Multiple instance variable assignments
- Recommend: Extract to form objects or domain models
Missing Test Detection
For each Ruby file in app/:
- Check for corresponding
_spec.rb or _test.rb
- Check for tested public methods
- Report untested files and methods
Analysis Commands
Use Claude Code's built-in tools instead of shell commands — they're faster, handle permissions correctly, and give better output:
- Find Ruby files by type: Use the Glob tool with patterns like
app/models/**/*.rb, app/controllers/**/*.rb, app/services/**/*.rb
- Find test files: Use Glob with
spec/**/*_spec.rb or test/**/*_test.rb
- Search for patterns in code: Use the Grep tool (e.g., search for
rescue\s*$, \.save\b, params\.permit!)
- Read and count lines in files: Use the Read tool to inspect files; count lines from the output
- Find long files: Use Glob to list all
app/**/*.rb files, then Read each to check line count
Report Output
Always save the audit report to RAILS_AUDIT_REPORT.md in the project root and present it to the user.
Source: thoughtbot/rails-audit-thoughtbot — distributed by TomeVault.
1---2name: rails-audit-thoughtbot3description: Perform comprehensive code audits of Ruby on Rails applications based on thoughtbot best practices. Use this skill when the user requests a code audit, code review, quality assessment, or analysis of a Rails application. The skill analyzes the entire codebase focusing on testing practices (RSpec), security vulnerabilities, code design (skinny controllers, domain models, PORO with ActiveModel), Rails conventions, database optimization, and Ruby best practices. Outputs a detailed markdown audit report grouped by category (Testing, Security, Models, Controllers, Code Design, Views) with severity levels (Critical, High, Medium, Low) within each category. Use when this capability is needed.4---56# Rails Audit Skill (thoughtbot Best Practices)78Perform comprehensive Ruby on Rails application audits based on thoughtbot's Ruby Science and Testing Rails best practices, with emphasis on Plain Old Ruby Objects (POROs) over Service Objects.910## Audit Scope1112The audit can be run in two modes:131. **Full Application Audit**: Analyze entire Rails application142. **Targeted Audit**: Analyze specific files or directories1516## Execution Flow1718### Step 1: Determine Audit Scope1920Ask user or infer from request:21- Full audit: Analyze all of `app/`, `spec/` or `test/`, `config/`, `db/`, `lib/`22- Targeted audit: Analyze specified paths only2324### Step 2: Collect Optional Metrics (SimpleCov + RubyCritic)2526Ask the user **both questions upfront** in a single `AskUserQuestion` so they can decide once:27- **Question**: "Before starting the audit, would you like to collect automated metrics?\n\n1. **SimpleCov** — runs your test suite to capture actual code coverage percentages\n2. **RubyCritic** — analyzes code complexity, duplication, and smells (does not run tests)\n\nBoth are recommended for the most thorough audit."28- **Options**: "Yes to both (Recommended)" / "SimpleCov only" / "RubyCritic only" / "Skip both"2930Based on the user's choice, spawn the accepted subagents **in parallel** using the Task tool. Both can run at the same time because SimpleCov modifies the test helper while RubyCritic only reads source files — they don't conflict.3132**SimpleCov subagent** (if accepted):3334> Read the file `agents/simplecov_agent.md` and follow all steps described in it. The audit scope is: {{SCOPE from Step 1}}. Return the coverage data in the output format specified in that file.3536**RubyCritic subagent** (if accepted):3738> Read the file `agents/rubycritic_agent.md` and follow all steps described in it. The audit scope is: {{SCOPE from Step 1}}. Return the code quality data in the output format specified in that file.3940**After both agents finish**, clean up:41- If SimpleCov ran: `rm -rf coverage/`42- If RubyCritic ran: `rm -rf tmp/rubycritic/`4344**Interpreting responses:**45- `COVERAGE_FAILED` / `RUBYCRITIC_FAILED`: no data for that tool — use estimation mode (SimpleCov) or omit the section (RubyCritic). Note the failure reason in the report.46- `COVERAGE_DATA`: parse and keep in context for Steps 4 and 5 (overall coverage, per-directory breakdowns, lowest-coverage files, zero-coverage files).47- `RUBYCRITIC_DATA`: parse and keep in context for Steps 4 and 5 (overall score, per-directory ratings, worst-rated files, top smells, most complex files).4849### Step 3: Load Reference Materials5051Before analyzing, read the relevant reference files:52- `references/code_smells.md` - Code smell patterns to identify53- `references/testing_guidelines.md` - Testing best practices54- `references/poro_patterns.md` - PORO and ActiveModel patterns55- `references/security_checklist.md` - Security vulnerability patterns56- `references/rails_antipatterns.md` - Rails-specific antipatterns (external services, migrations, performance)5758### Step 4: Analyze Code by Category5960Analyze in this order:61621. **Testing Coverage & Quality**63 - If SimpleCov data was collected in Step 2, use actual coverage percentages instead of estimates64 - Cross-reference per-file SimpleCov data: files with 0% coverage = "missing tests"65 - Check for missing test files66 - Identify untested public methods67 - Review test structure (Four Phase Test)68 - Check for testing antipatterns69702. **Security Vulnerabilities**71 - SQL injection risks72 - Mass assignment vulnerabilities73 - XSS vulnerabilities74 - Authentication/authorization issues75 - Sensitive data exposure76773. **Models & Database**78 - Fat model detection79 - Missing validations80 - N+1 query risks81 - Callback complexity82 - Law of Demeter violations (voyeuristic models)83 - If RubyCritic data was collected, flag models with D/F ratings or high complexity84854. **Controllers**86 - Fat controller detection87 - Business logic in controllers88 - Missing strong parameters89 - Response handling90 - Monolithic controllers (non-RESTful actions, > 7 actions)91 - Bloated sessions (storing objects instead of IDs)92 - If RubyCritic data was collected, flag controllers with D/F ratings or high complexity93945. **Code Design & Architecture**95 - Service Objects → recommend PORO refactoring96 - Large classes97 - Long methods98 - Feature envy99 - Law of Demeter violations100 - Single Responsibility violations101 - If RubyCritic data was collected, cross-reference D/F rated files and high-complexity files with manual code review findings1021036. **Views & Presenters**104 - Logic in views (PHPitis)105 - Missing partials for DRY106 - Helper complexity107 - Query logic in views1081097. **External Services & Error Handling**110 - Fire and forget (missing exception handling for HTTP calls)111 - Sluggish services (missing timeouts, synchronous calls that should be backgrounded)112 - Bare rescue statements113 - Silent failures (save without checking return value)1141158. **Database & Migrations**116 - Messy migrations (model references, missing down methods)117 - Missing indexes on foreign keys, polymorphic associations, uniqueness validations118 - Performance antipatterns (Ruby iteration vs SQL queries)119 - Bulk operations without transactions120121### Step 5: Generate Audit Report122123Create `RAILS_AUDIT_REPORT.md` in project root with structure defined in `references/report_template.md`.124125When SimpleCov coverage data was collected in Step 2, use the **SimpleCov variant** of the Testing section in the report template. When coverage data is not available, use the **estimation variant**.126127When RubyCritic data was collected in Step 2b, include the **Code Quality Metrics** section in the report using the RubyCritic variant from the report template. When RubyCritic data is not available, use the **not available variant**.128129## Severity Definitions130131- **Critical**: Security vulnerabilities, data loss risks, production-breaking issues132- **High**: Performance issues, missing tests for critical paths, major code smells133- **Medium**: Code smells, convention violations, maintainability concerns134- **Low**: Style issues, minor improvements, suggestions135136## Key Detection Patterns137138### Service Object → PORO Refactoring139140When you find classes in `app/services/`:141- Classes named `*Service`, `*Manager`, `*Handler`142- Classes with only `.call` or `.perform` methods143- Recommend: Rename to domain nouns, include `ActiveModel::Model`144145### Fat Model Detection146147Models with:148- More than 200 lines149- More than 15 public methods150- Multiple unrelated responsibilities151- Recommend: Extract to POROs using composition152153### Fat Controller Detection154155Controllers with:156- Actions over 15 lines157- Business logic (not request/response handling)158- Multiple instance variable assignments159- Recommend: Extract to form objects or domain models160161### Missing Test Detection162163For each Ruby file in `app/`:164- Check for corresponding `_spec.rb` or `_test.rb`165- Check for tested public methods166- Report untested files and methods167168## Analysis Commands169170Use Claude Code's built-in tools instead of shell commands — they're faster, handle permissions correctly, and give better output:171172- **Find Ruby files by type**: Use the Glob tool with patterns like `app/models/**/*.rb`, `app/controllers/**/*.rb`, `app/services/**/*.rb`173- **Find test files**: Use Glob with `spec/**/*_spec.rb` or `test/**/*_test.rb`174- **Search for patterns in code**: Use the Grep tool (e.g., search for `rescue\s*$`, `\.save\b`, `params\.permit!`)175- **Read and count lines in files**: Use the Read tool to inspect files; count lines from the output176- **Find long files**: Use Glob to list all `app/**/*.rb` files, then Read each to check line count177178## Report Output179180Always save the audit report to `RAILS_AUDIT_REPORT.md` in the project root and present it to the user.181182---183> Source: [thoughtbot/rails-audit-thoughtbot](https://github.com/thoughtbot/rails-audit-thoughtbot) — distributed by [TomeVault](https://tomevault.io).184<!-- tomevault:4.0:skill_md:2026-07-01 -->