Skill v1.0.1
currentLLM-judged scan100/1004 files
version: "1.0.1" name: rspec-testing description: This skill should be used when writing, reviewing, or improving RSpec tests for Ruby on Rails applications. Use this skill for all testing tasks including model specs, controller specs, system specs, component specs, service specs, and integration tests. The skill provides comprehensive RSpec best practices from Better Specs and thoughtbot guides.
RSpec Testing for Rails
Overview
Write comprehensive, maintainable RSpec tests following industry best practices. This skill combines guidance from Better Specs and thoughtbot's testing guides to produce high-quality test coverage for Rails applications.
Core Testing Principles
1. Test-Driven Development (TDD)
Follow the Red-Green-Refactor cycle:
- Red: Write failing tests that define expected behavior
- Green: Implement minimal code to make tests pass
- Refactor: Improve code while tests continue to pass
2. Test Structure (Arrange-Act-Assert)
Organize tests with clear phases separated by newlines:
it 'creates a new article' do# Arrange - set up test datauser = create(:user)attributes = {title: 'Test Article', body: 'Content here'}# Act - perform the actionarticle = Article.create(attributes)# Assert - verify the outcomeexpect(article).to be_persistedexpect(article.title).to eq('Test Article')end
3. Single Responsibility
Each test should verify one behavior. For unit tests, use one expectation per test. For integration tests, multiple expectations are acceptable when testing a complete flow.
4. Test Real Behavior
Avoid over-mocking. Test actual application behavior when possible. Only stub external services, slow operations, and dependencies outside your control.
Test Type Decision Tree
When to Write Model Specs
Use model specs (spec/models/) for:
- Validations
- Associations
- Scopes
- Instance methods
- Class methods
- Enums and constants
- Database constraints
Example:
# spec/models/article_spec.rbRSpec.describe Article dodescribe 'validations' doit 'validates presence of title' doarticle = build(:article, title: nil)expect(article).not_to be_validexpect(article.errors[:title]).to include("can't be blank")endenddescribe 'associations' doit { is_expected.to belong_to(:user) }it { is_expected.to have_many(:comments) }enddescribe '#published?' doit 'returns true when status is published' doarticle = build(:article, status: :published)expect(article.published?).to be trueendendend
When to Write Controller Specs
Use controller specs (spec/controllers/) for:
- Authorization checks (Pundit/CanCanCan)
- Request routing and parameter handling
- Response status codes
- Instance variable assignments
- Flash messages
- Redirects
Example:
# spec/controllers/articles_controller_spec.rbRSpec.describe ArticlesController dodescribe 'POST #create' docontext 'with valid parameters' doit 'creates a new article and redirects' douser = create(:user)session[:user_id] = user.idvalid_attributes = {title: 'Test Article',body: 'Article content'}expect dopost :create, params: {article: valid_attributes}end.to change(Article, :count).by(1)expect(response).to redirect_to(Article.last)endendcontext 'with invalid parameters' doit 'does not create article and renders new template' douser = create(:user)session[:user_id] = user.idinvalid_attributes = {title: '', body: ''}expect dopost :create, params: {article: invalid_attributes}end.not_to change(Article, :count)expect(response).to render_template(:new)endendendend
When to Write System Specs
Use system specs (spec/system/) for:
- End-to-end user workflows
- Multi-step interactions
- JavaScript functionality
- Form submissions
- Navigation flows
- Real user scenarios
Naming convention: user_action_spec.rb or feature_description_spec.rb
Example:
# spec/system/article_creation_spec.rbRSpec.describe 'Article Creation' doit 'allows a user to create a new article' douser = create(:user)# Sign invisit '/login'fill_in 'Email', with: user.emailfill_in 'Password', with: 'password'click_button 'Sign In'# Navigate to new article pageclick_link 'New Article'expect(page).to have_current_path(new_article_path)# Fill out the article formfill_in 'Title', with: 'My Test Article'fill_in 'Body', with: 'This is the article content'select 'Published', from: 'Status'# Submit the formclick_button 'Create Article'expect(page).to have_content('Article created successfully!')expect(page).to have_content('My Test Article')endend
When to Write Component Specs
Use component specs (spec/components/) for:
- ViewComponent rendering
- Variant behavior
- Slot functionality
- Conditional rendering
- Component attributes
Example:
# spec/components/button_component_spec.rbRSpec.describe ButtonComponent, type: :component dodescribe 'variants' doit 'renders primary variant' dorender_inline(described_class.new(variant: :primary)) { 'Click me' }button = page.find('button')expect(button[:class]).to include('btn-primary')expect(page).to have_button('Click me')endit 'renders secondary variant' dorender_inline(described_class.new(variant: :secondary)) { 'Cancel' }button = page.find('button')expect(button[:class]).to include('btn-secondary')endendend
When to Write Service/Integration Specs
Use service/integration specs (spec/services/, spec/integration/) for:
- Complex business logic
- Multi-step workflows
- External API integrations
- Background job processing
- Data transformations
RSpec Syntax & Style Guide
Describe Blocks
Use Ruby documentation conventions:
.method_namefor class methods#method_namefor instance methods
describe '.find_by_title' do # class methoddescribe '#publish' do # instance methoddescribe 'validations' do # grouping
Context Blocks
Start with "when," "with," or "without":
context 'when user is admin' docontext 'with valid parameters' docontext 'without authentication' do
It Blocks
- Keep descriptions under 40 characters
- Use third-person present tense
- Never use "should" in descriptions
# ✅ Goodit 'creates a new article' doit 'validates presence of title' doit 'redirects to dashboard' do# ❌ Badit 'should create a new article' doit 'should validate presence of title' do
Expectations
Always use expect syntax (never should):
# ✅ Goodexpect(article).to be_validexpect(response).to have_http_status(:success)expect { action }.to change(Article, :count).by(1)# ❌ Bad (deprecated)article.should be_validresponse.should have_http_status(:success)
One-Liners
Use is_expected for concise one-line specs:
subject { article }it { is_expected.to be_valid }it { is_expected.to be_persisted }
System Test Best Practices
Authentication in System Tests
Test authentication flows directly without stubbing:
# Good - test the actual login flowvisit '/login'fill_in 'Email', with: user.emailfill_in 'Password', with: 'password'click_button 'Sign In'expect(page).to have_content('Dashboard')
Controller Test Authentication
For controller tests, use direct session assignment rather than stubbing:
# ✅ Good - direct session assignmentsession[:user_id] = user.id# ❌ Avoid - stubbing authenticationallow_any_instance_of(Controller).to receive(:logged_in?).and_return(true)
Avoid CSS Class Testing
Don't test implementation details like CSS utility classes. Test semantic selectors and content:
# ✅ Good - semantic selectorsexpect(page).to have_selector(:test_id, 'user-modal')expect(page).to have_css("[aria-hidden='false']")expect(page).to have_content('Success message')expect(page).to have_button('Submit')# ❌ Bad - coupling to CSS implementationexpect(page).to have_css('.opacity-100')expect(page).to have_css('.bg-red-500')expect(page).to have_css('.rounded-lg')
Factory Patterns
Organization
- Associations (implicit) first
- Attributes (alphabetical)
- Traits (alphabetical)
FactoryBot.define dofactory :article do# Associationsusercategory# Attributes (alphabetical)body { 'Article content goes here...' }published_at { Time.current }status { :draft }title { 'Sample Article Title' }# Traits (alphabetical)trait :published dostatus { :published }published_at { 1.day.ago }endtrait :with_tags doafter(:create) do |article|create_list(:tag, 3, article: article)endendendend
Prefer Build Over Create
Use build and build_stubbed when database persistence isn't needed:
# ✅ Good - fast, no database hitit 'validates title format' doarticle = build(:article, title: '')expect(article).not_to be_validend# Less optimal - unnecessary database hitit 'validates title format' doarticle = create(:article, title: '')expect(article).not_to be_validend
Common Testing Patterns
Testing Validations
describe 'validations' doit 'validates presence of title' doarticle = build(:article, title: nil)expect(article).not_to be_validexpect(article.errors[:title]).to include("can't be blank")endit 'validates length of title' doarticle = build(:article, title: 'a' * 256)expect(article).not_to be_validendit 'allows valid titles' doarticle = build(:article, title: 'Valid Title')expect(article).to be_validendend
Testing Enums
describe 'enums' doit 'defines status enum' doexpect(described_class.statuses).to eq({'draft' => 'draft','published' => 'published','archived' => 'archived'})endit 'has correct default' doarticle = described_class.newexpect(article.status).to eq('draft')endend
Testing Authorization
context 'when user is not admin' doit 'raises authorization error' douser = create(:user, role: :member)session[:user_id] = user.idexpect doget :admin_dashboardend.to raise_error(Pundit::NotAuthorizedError)endend
Using Shoulda Matchers
describe 'associations' doit { is_expected.to belong_to(:user) }it { is_expected.to have_many(:comments) }enddescribe 'validations' doit { is_expected.to validate_presence_of(:title) }it { is_expected.to validate_length_of(:title).is_at_most(255) }end
What to Avoid
❌ Don't Stub the System Under Test
Never mock or stub methods on the class being tested:
# ❌ Badit 'processes payment' doorder = Order.newallow(order).to receive(:calculate_total).and_return(100)expect(order.process_payment).to be trueend# ✅ Goodit 'processes payment' doorder = Order.new(line_items: [line_item])expect(order.process_payment).to be trueend
❌ Don't Test Private Methods
Test the public interface. Private methods are tested indirectly:
# ❌ Baddescribe '#calculate_total (private)' doit 'sums line items' doorder.send(:calculate_total)endend# ✅ Gooddescribe '#total' doit 'returns sum of line items' doexpect(order.total).to eq(100)endend
❌ Avoid any_instance_of
Use dependency injection instead:
# ❌ Badallow_any_instance_of(PaymentService).to receive(:charge)# ✅ Goodpayment_service = instance_double(PaymentService)allow(payment_service).to receive(:charge).and_return(success)order = Order.new(payment_service: payment_service)
Quick Reference
Test Organization
RSpec.describe ClassName do# Setup (let, before)let(:resource) { create(:resource) }before do# common setupend# Validationsdescribe 'validations' doend# Associationsdescribe 'associations' doend# Class methodsdescribe '.class_method' doend# Instance methodsdescribe '#instance_method' docontext 'when condition' doit 'does something' doendendendend
Expectation Matchers
# Equalityexpect(value).to eq(expected)expect(value).to be(expected) # same objectexpect(value).to match(/regex/)# Predicatesexpect(object).to be_validexpect(object).to be_persistedexpect(collection).to be_empty# Collectionsexpect(array).to include(item)expect(array).to contain_exactly(1, 2, 3)expect(hash).to have_key(:name)# Changesexpect { action }.to change(Model, :count).by(1)expect { action }.to change { object.attribute }.from(old).to(new)# Errorsexpect { action }.to raise_error(ErrorClass)expect { action }.not_to raise_error
Resources
This skill includes detailed reference documentation in the references/ directory:
references/better_specs_guide.md
Comprehensive patterns from Better Specs including:
- Describe/context/it block conventions
- Subject and let usage
- Mocking strategies
- Shared examples
- Factory patterns
references/thoughtbot_patterns.md
thoughtbot's RSpec best practices covering:
- Modern RSpec syntax
- Test structure and organization
- What to avoid in tests
- Capybara patterns for system tests
- Factory organization
Load these references when you need detailed examples or are unsure about a specific pattern.