npx skills add ...
npx skills add thinkoodle/rails-skills --skill testing
Expert guidance for Rails testing infrastructure, test types, and what to test. Use when writing tests, setting up a test suite, choosing between test types, configuring system tests (Capybara), request tests, integration tests, helper tests, mailer tests, job tests, Action Cable tests, parallel testing, CI setup, test database management, or improving test coverage. Covers the test runner, fixtures vs factories, parallel testing, system tests (drivers, screenshots), request tests, controller tests (legacy), helper tests, mailer tests, job tests, Action Cable tests, test coverage, CI patterns, and test database strategies. Trigger on "test", "testing", "test suite", "system test", "request test", "integration test", "test runner", "parallel testing", "capybara", "test database", "CI testing", "test coverage".
npx skills add thinkoodle/rails-skills --skill testing
Build fast, reliable, maintainable test suites for Rails applications. This skill covers the Rails testing ecosystem — test types, infrastructure, and what to test where.
Companion skill: For Minitest-specific assertions, fixtures deep-dive, TDD workflow, and RSpec-to-Minitest conversion, see the minitest skill.
Most agent mistakes come from inverting this pyramid. Writing system tests for everything is the #1 mistake. System tests are 10-100x slower than unit tests. A single flaky system test wastes more time than 50 model tests.
This is the most important decision. Get this wrong and you waste time writing slow, brittle tests.
| Test Type | Base Class | Speed | Use For |
|---|---|---|---|
| Model | ActiveSupport::TestCase | ⚡ Fast | Validations, scopes, business logic, callbacks |
| Service/PORO | ActiveSupport::TestCase | ⚡ Fast | Service objects, form objects, query objects |
| Job | ActiveJob::TestCase | ⚡ Fast | Job behavior, enqueuing, retries |
| Mailer | ActionMailer::TestCase | ⚡ Fast | Email content, recipients, attachments |
| Helper | ActionView::TestCase | ⚡ Fast | View helper output |
| Request | ActionDispatch::IntegrationTest | 🔶 Medium | HTTP request/response cycle, API endpoints |
| Integration | ActionDispatch::IntegrationTest | 🔶 Medium | Multi-step workflows without a browser |
| Channel | ActionCable::Channel::TestCase | ⚡ Fast | Channel subscriptions, streams |
| Connection | ActionCable::Connection::TestCase | ⚡ Fast | WebSocket auth, connection identifiers |
| System | ActionDispatch::SystemTestCase | 🐌 Slow | JS interactions, critical E2E user paths |
| Flag | Purpose |
|---|---|
-n PATTERN | Filter tests by name (string or /regex/) |
-f / --fail-fast | Stop on first failure |
-v / --verbose | Show each test name |
-b / --backtrace | Full backtrace (not just app lines) |
--profile [N] | List N slowest tests (default 10) |
-p / --pride | Rainbow output 🌈 |
-S / --skip CODES | Skip reporting types (e.g., E for errors) |
Request tests simulate full HTTP requests through the middleware stack. Use these instead of controller tests for new code.
response / response.body / response.parsed_bodycookies, flash, session@controller, @request, @responseSee
references/request-tests.mdfor JSON API tests, Turbo Stream tests, file uploads, auth patterns, and DOM assertions.
System tests run in a real browser via Capybara. Reserve for critical paths that require JavaScript or complex UI interaction.
✅ User registration/login flow ✅ Checkout/payment flow ✅ Complex JS interactions (drag-and-drop, modals, live search) ✅ Turbo/Stimulus-dependent features ✅ File upload with preview
❌ CRUD operations (use request tests)
❌ Validation error display (use request tests + assert_select)
❌ API endpoints (use request tests)
❌ Anything testable without a browser
Driver options:
| Driver | Browser | Use Case |
|---|---|---|
:selenium + :headless_chrome | Chrome (headless) | Default, CI-friendly |
:selenium + :headless_firefox | Firefox (headless) | Alternative |
:selenium + :chrome | Chrome (visible) | Debugging |
:cuprite | Chrome via CDP | Faster, no Selenium overhead |
assert_text, assert_selector auto-wait — use them instead of page.has_css?assert_text "Done", wait: 5sleep — always use Capybara's wait-aware assertionstake_screenshot for debugging; failed tests auto-capture to tmp/screenshots/See
references/system-tests.mdfor Capybara DSL reference, Cuprite setup, JS interaction patterns, and Turbo/Stimulus testing.
From request tests: assert_emails 1 { post users_url, params: {...} }
Enqueued: assert_enqueued_email_with UserMailer, :welcome, args: [user] { ... }
See
references/helpers-and-assertions.mdfor multipart emails, attachments, parameterized mailers, and previews.
Verify enqueuing from other code:
See
references/helpers-and-assertions.mdfor job queue assertions, filtering, chained jobs, and exception testing.
Broadcast assertions (usable in any test): include ActionCable::TestHelper then use assert_broadcast_on, assert_broadcasts.
See
references/helpers-and-assertions.mdfor stream assertions, custom channel methods, and broadcast testing from models.
By default, each test runs in a database transaction that rolls back after completion. This keeps tests isolated without manual cleanup.
Disable when needed (e.g., testing multi-threaded code):
Creates separate test databases (test-database-0, test-database-1, etc.) per worker.
Use for JRuby/TruffleRuby, or when process forking is expensive.
Use parallelize_setup/parallelize_teardown hooks for per-worker setup. Default threshold is 50 tests (won't parallelize below that). Customize with config.active_support.test_parallelization_threshold = 100.
See
references/parallel-testing.mdfor process vs thread comparison, hooks, and common parallel testing issues.
CI tips: Parallelize with PARALLEL_WORKERS, separate system tests into their own CI job, cache gems/node_modules, use headless Chrome, add a Zeitwerk eager-load test.
See
references/ci.mdfor full GitHub Actions YAML and CI patterns.
See
references/parallel-testing.mdfor detailed time testing patterns, common pitfalls, and flaky test fixes.
validates :name, presence: true works; test YOUR business logicassert_received(:method) ties tests to internalssleep 2 in system tests; use Capybara's built-in waitingassert_equal Time.current, record.created_at is flaky| What | Test Type | Example |
|---|---|---|
| Model validation | Model test | refute User.new(email: nil).valid? |
| Model scope | Model test | assert_includes User.active, @user |
| Business logic method | Model/Service test | assert_equal 42, order.total |
| API endpoint | Request test | get api_users_url, as: :json |
| Page renders correctly | Request test | get root_url; assert_response :success |
| Form submission | Request test | post articles_url, params: {...} |
| Auth/authorization | Request test | get admin_url; assert_response :redirect |
| Email content | Mailer test | assert_equal "Welcome", email.subject |
| Email gets sent | Request test | assert_emails 1 { post ... } |
| Job behavior | Job test | perform_enqueued_jobs { MyJob.perform_later } |
| Job gets enqueued | Model/Request test | assert_enqueued_with(job: MyJob) { ... } |
| JS-dependent flow | System test | click_on "Submit"; assert_text "Done" |
| View helper | Helper test | assert_equal "$10", format_price(10) |
| WebSocket channel | Channel test | subscribe; assert_has_stream "room_1" |
test/
├── test_helper.rb # Global config
├── application_system_test_case.rb # System test base (created on first system test)
├── controllers/ # Controller/functional tests (legacy — prefer request tests)
├── fixtures/ # YAML fixture data
│ ├── users.yml
│ ├── files/ # File fixtures for uploads
│ └── action_text/rich_texts.yml # Action Text fixtures
├── helpers/ # View helper tests
├── integration/ # Integration tests
├── jobs/ # Job tests
├── mailers/ # Mailer tests
│ └── previews/ # Mailer previews (not tests, but useful)
├── models/ # Model tests (bulk of your tests)
├── channels/ # Action Cable channel tests
│ └── application_cable/ # Connection tests
├── requests/ # Request tests (preferred over controllers/)
├── services/ # Service object tests
├── system/ # System tests (keep small)
└── support/ # Shared test helpers# Run everything (excludes system tests)
bin/rails test
# Run system tests separately
bin/rails test:system
# Run ALL tests including system
bin/rails test:all
# Run a single file
bin/rails test test/models/user_test.rb
# Run a specific test by line number
bin/rails test test/models/user_test.rb:42
# Run a line range
bin/rails test test/models/user_test.rb:10-30
# Run by name pattern
bin/rails test -n /password/
# Run a directory
bin/rails test test/models/
# Fail fast — stop on first failure
bin/rails test --fail-fast
# Verbose output
bin/rails test -v
# Profile slow tests
bin/rails test --profile
# Set seed for reproducibility
bin/rails test --seed 12345class ArticlesRequestTest < ActionDispatch::IntegrationTest
setup do
@user = users(:admin)
@article = articles(:published)
end
test "GET /articles returns success" do
get articles_url
assert_response :success
end
test "POST /articles creates with valid params" do
sign_in @user
assert_difference "Article.count", 1 do
post articles_url, params: { article: { title: "New", body: "Content" } }
end
assert_redirected_to article_url(Article.last)
end
test "POST /articles rejects invalid params" do
sign_in @user
assert_no_difference "Article.count" do
post articles_url, params: { article: { title: "" } }
end
assert_response :unprocessable_entity
end
end# test/application_system_test_case.rb
require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :headless_chrome
endrequire "application_system_test_case"
class CheckoutTest < ApplicationSystemTestCase
test "user completes checkout" do
user = users(:buyer)
product = products(:widget)
visit new_session_path
fill_in "Email", with: user.email
fill_in "Password", with: "password"
click_on "Sign in"
visit product_path(product)
click_on "Add to Cart"
click_on "Checkout"
fill_in "Card number", with: "4242424242424242"
click_on "Pay"
assert_text "Order confirmed"
end
endclass UserMailerTest < ActionMailer::TestCase
test "welcome email" do
email = UserMailer.welcome(users(:new_user))
assert_emails 1 do
email.deliver_now
end
assert_equal ["noreply@example.com"], email.from
assert_equal [users(:new_user).email], email.to
assert_equal "Welcome!", email.subject
assert_match users(:new_user).name, email.body.to_s
end
endclass ProcessOrderJobTest < ActiveJob::TestCase
test "charges the account" do
perform_enqueued_jobs do
ProcessOrderJob.perform_later(orders(:pending))
end
assert orders(:pending).reload.charged?
end
endclass OrderTest < ActiveSupport::TestCase
include ActiveJob::TestHelper
test "#place enqueues processing job" do
assert_enqueued_with(job: ProcessOrderJob) do
orders(:new).place!
end
end
endclass CurrencyHelperTest < ActionView::TestCase
test "formats USD" do
assert_equal "$10.00", format_price(1000, "USD")
end
test "handles zero" do
assert_equal "$0.00", format_price(0, "USD")
end
end# Channel test
class ChatChannelTest < ActionCable::Channel::TestCase
test "subscribes to room stream" do
subscribe room: "general"
assert subscription.confirmed?
assert_has_stream "chat_general"
end
end
# Connection test
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
test "connects with valid user" do
cookies.signed[:user_id] = users(:admin).id
connect
assert_equal users(:admin).id, connection.current_user.id
end
test "rejects without auth" do
assert_reject_connection { connect }
end
end# After migrations, sync test DB schema
bin/rails db:test:prepare
# Or recreate from scratch
bin/rails db:test:purge db:test:prepare
# Rails auto-checks for pending migrations before tests runclass ThreadedTest < ActiveSupport::TestCase
self.use_transactional_tests = false
teardown do
# Manual cleanup needed!
User.delete_all
end
end# test/test_helper.rb
class ActiveSupport::TestCase
parallelize(workers: :number_of_processors)
end# Override worker count
PARALLEL_WORKERS=4 bin/rails testclass ActiveSupport::TestCase
parallelize(workers: :number_of_processors, with: :threads)
end# config/environments/test.rb
config.eager_load = ENV["CI"].present?# CI steps
bin/rails db:test:prepare
bin/rails test # Unit + request tests
bin/rails test:system # System tests (separate job recommended)freeze_time do ... end # Freeze at current moment
travel_to Time.zone.local(2024, 1, 15) do ... end # Travel to specific time
travel 3.days do ... end # Travel forward
travel_back # Return to real time