Skip to content
Skills Library
Programming · Testing

rspec

/rspec

This skill should be used when the user asks to "write specs", "create spec", "add RSpec tests", "fix failing spec", or mentions RSpec, describe blocks, it blocks, expect syntax, test doubles, or matchers. Should also be used when editing *_spec.rb files, working in spec/ directory, planning implementation phases that include tests (TDD/RGRC workflow), writing Testing Strategy or Success Criteria sections, discussing unit or integration tests, or reviewing spec output and test failures. Comprehensive RSpec and FactoryBot reference with best practices, ready-to-use patterns, and examples.

Licence
MIT
Last repository change
07.09.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
55
Scripts
49
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 07.09.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What to check before installing
  • 49 scripts in this package. Review them before installing, as Claude may execute them.

Scripts: examples/core/basic_structure.rb, examples/core/configuration.rb, examples/core/hooks.rb, examples/core/memoized_helpers.rb, examples/core/metadata_filtering.rb, examples/core/shared_examples.rb, examples/factory_bot/associations.rb, examples/factory_bot/build_strategies.rb

What it does and when to use it

This skill should be used when the user asks to "write specs", "create spec", "add RSpec tests", "fix failing spec", or mentions RSpec, describe blocks, it blocks, expect syntax, test doubles, or matchers. Should also be used when editing *_spec.rb files, working in spec/ directory, planning implementation phases that include tests (TDD/RGRC workflow), writing Testing Strategy or Success Criteria sections, discussing unit or integration tests, or reviewing spec output and test failures. Comprehensive RSpec and FactoryBot reference with best practices, ready-to-use patterns, and examples.

Triggers from the description

write specscreate specadd RSpec testsfix failing spec
Original author description

This skill should be used when the user asks to "write specs", "create spec", "add RSpec tests", "fix failing spec", or mentions RSpec, describe blocks, it blocks, expect syntax, test doubles, or matchers. Should also be used when editing *_spec.rb files, working in spec/ directory, planning implementation phases that include tests (TDD/RGRC workflow), writing Testing Strategy or Success Criteria sections, discussing unit or integration tests, or reviewing spec output and test failures. Comprehensive RSpec and FactoryBot reference with best practices, ready-to-use patterns, and examples.

How it works

  1. Quick Reference
  2. Writing Good Specs
  3. Common Matchers
  4. Test Doubles
  5. Rails Specs
  6. Best Practices
  7. Configuration
  8. Before You Write
Original SKILL.md headings · 337 lines, 1,205 words
SKILL.md preview
---
name: rspec
version: 1.1.2
description: >-
  This skill should be used when the user asks to "write specs", "create spec",
  "add RSpec tests", "fix failing spec", or mentions RSpec, describe blocks, it
  blocks, expect syntax, test doubles, or matchers. Should also be used when
  editing *_spec.rb files, working in spec/ directory, planning implementation
  phases that include tests (TDD/RGRC workflow), writing Testing Strategy or
  Success Criteria sections, discussing unit or integration tests, or reviewing
  spec output and test failures. Comprehensive RSpec and FactoryBot reference
  with best practices, ready-to-use patterns, and examples.
---

# RSpec Testing

This skill provides comprehensive guidance for writing effective RSpec tests in Ruby and Rails applications. Use for writing new specs, fixing failing tests, understanding matchers, using test doubles, and following RSpec best practices.

## Quick Reference

### Basic Structure

```ruby
RSpec.describe Order do
  subject(:order) { described_class.new(items) }
  let(:items) { [item1, item2] }
  let(:item1) { double("item", price: 10) }
  let(:item2) { double("item", price: 20) }

  describe "#total" do
    it "sums item prices" do
      expect(order.total).to eq(30)
    end
  end

  context "with discount" do
    let(:order) { described_class.new(items, discount: 5) }

    it "applies discount" do
      expect(order.total).to eq(25)
    end
  end
end
```

### Key Concepts

| Concept | Purpose |
|---------|---------|
| `describe` / `context` | Group related examples |
| `it` / `specify` | Define individual test cases |
| `let` | Lazy-evaluated, memoized helper |
| `let!` | Eager-evaluated helper (runs before each example) |
| `subject` | Primary object under test |
| `before` / `after` | Setup and teardown hooks |
| `expect` | Make assertions |

## Writing Good Specs

### Use Named Subject for Method Tests

```ruby
describe "#calculate_total" do
  subject(:total) { order.calculate_total }

  it "returns sum of items" do
    expect(total).to eq(100)
  end
end
```

### Context Blocks for Different States

```ruby
describe "#withdraw" do
  context "with sufficient funds" do
    let(:account) { build(:account, balance: 100) }

    it "reduces balance" do
      expect { account.withdraw(50) }.to change(account, :balance).by(-50)
    end
  end

  context "with insufficient funds" do
    let(:account) { build(:account, balance: 10) }

    it "raises error" do
      expect { account.withdraw(50) }.to raise_error(InsufficientFunds)
    end
  end
end
```

## Common Matchers

### Equality

```ruby
expect(x).to eq(y)          # ==
expect(x).to eql(y)         # eql? (type-sensitive)
expect(x).to be(y)          # equal? (identity)
```

### Truthiness

```ruby
expect(x).to be_truthy      # not nil or false
expect(x).to be_falsey      # nil or false
expect(x).to be_nil
expect(x).to be true        # exactly true
```

### Comparisons

```ruby
expect(x).to be > 3
expect(x).to be_between(1, 10).inclusive
expect(x).to be_within(0.1).of(3.14)
```

### Collections

```ruby
expect(arr).to include(1, 2)
expect(arr).to contain_exactly(3, 2, 1)  # order-independent
expect(arr).to all(be_positive)
expect(str).to start_with("hello")
expect(hash).to have_key(:name)
```

### Changes

```ruby
expect { x += 1 }.to change { x }.by(1)
expect { x += 1 }.to change { x }.from(0).to(1)
expect { user.save }.to change(User, :count).by(1)
```

### Errors

```ruby
expect { raise "boom" }.to raise_error
expect { raise ArgumentError, "bad" }.to raise_error(ArgumentError, /bad/)
```

### Predicates (Dynamic)

```ruby
expect([]).to be_empty      # [].empty?
expect(user).to be_valid    # user.valid?
expect(hash).to have_key(k) # hash.has_key?(k)
```

## Test Doubles

### Types

```ruby
# Basic double (strict)
user = double("user", name: "Bob")

# Verifying doubles (recommended)
user = instance_double("User", name: "Bob")  # validates instance methods
api = class_double("Api", fetch: data)       # validates class methods
logger = object_double(Rails.logger)         # validates object methods

# Spy (null object for after-the-fact verification)
notifier = spy("notifier")
```

### Stubbing

```ruby
allow(user).to receive(:name).and_return("Bob")
allow(Api).to receive(:fetch).and_return(data)
allow(obj).to receive(:method) { computed_value }
```

### Expectations

```ruby
expect(user).to receive(:save).and_return(true)
expect(Api).to receive(:post).with(hash_including(id: 1))

# Spy pattern (verify after action)
notifier = spy("notifier")
service.call(notifier)
expect(notifier).to have_received(:notify).with("done")
```

### Argument Matchers

```ruby
expect(obj).to receive(:call).with(anything)
expect(obj).to receive(:call).with(kind_of(Integer))
expect(obj).to receive(:call).with(hash_including(a: 1))
expect(obj).to receive(:call).with(array_including(1, 2))
```

## Rails Specs

| Spec Type | Use For | Key Helpers |
|-----------|---------|-------------|
| `type: :model` | Business logic, scopes, validations | `build`, `create`, associations |
| `type: :request` | Controller actions (preferred) | `get`, `post`, `response`, `have_http_status` |
| `type: :system` | Browser/UI testing | `visit`, `fill_in`, `click_button`, `have_text` |
| `type: :job` | Background jobs | `have_enqueued_job`, `perform_now` |
| `type: :mailer` | Email delivery | `have_enqueued_mail`, `deliver_now` |
| `type: :routing` | Route resolution | `route_to`, `be_routable` |

See `examples/rails/` for complete spec templates.

## Best Practices

### Do

- Use `described_class` instead of hardcoding class name
- Use `let` for test data, `let!` when database records must exist before test
- Use **named subject** when referencing in tests: `subject(:user) { ... }`
- Use context blocks to organize different scenarios
- Use verifying doubles (`instance_double`) over plain `double`
- Name examples with verbs: `it "creates user"` not `it "should create user"`
- Keep examples focused on one behavior
- Use factories over fixtures for flexible test data
- Prefer `build_stubbed` or `build` over `create` when database not needed

### Don't

- Don't use instance variables (`@user`) - use `let` for type safety
- Don't use `before` just to trigger `let` evaluation - use `let!` instead:
  ```ruby
  # BAD - before just to initialize
  let(:user) { create(:user) }
  before { user }

  # GOOD - let! for eager evaluation
  let!(:user) { create(:user) }
  ```
  Use `before` for side-effects like `sign_in(user)` or `driven_by(:rack_test)`
- Don't use `let!` when `let` suffices (wastes resources)
- Don't test Rails framework (validations work, focus on business logic)
- Don't stub the object under test
- Avoid `any_instance_of` - prefer stubbing `ClassName.new` to return a double (see `references/mocks.md`)
- Don't use `receive_message_chain` (violates Law of Demeter)
- Don't write examples without descriptions
- Shared examples work best for testing concerns across including classes. For unique behaviors, prefer repetition over abstraction

### Factory Bot

```ruby
# Build strategies
user = build(:user)              # In-memory, not persisted
user = create(:user)             # Persisted to database
user = build_stubbed(:user)      # Fake persisted (fastest)
attrs = attributes_for(:user)    # Hash of attributes

# With traits and attributes
user = create(:user, :admin, :verified, name: "Bob")

# Lists
users = create_list(:user, 5, :admin)
```

**Strategy Selection**:
- `build_stubbed` - Unit tests without database (fastest)
- `build` - Validation tests, method tests
- `create` - Database queries, scopes, associations
- `attributes_for` - Controller params

See `references/factory_bot.md` for traits, sequences, associations, and callbacks.

## Configuration

Essential settings for `spec_helper.rb` and `rails_helper.rb`:

| Setting | Purpose |
|---------|---------|
| `verify_partial_doubles = true` | Validates stubbed methods exist |
| `filter_run_when_matching :focus` | Run only focused specs (`fit`, `fdescribe`) |
| `order = :random` | Randomize spec order to catch dependencies |
| `use_transactional_fixtures = true` | Rollback database after each spec |
| `infer_spec_type_from_file_location!` | Auto-detect spec type from path |

See `examples/core/configuration.rb` for complete setup.

## Before You Write

**What are you about to do?**

```
├── Creating or modifying a factory?
│   └── Read `references/factory_bot.md`
│
├── Writing a new spec file?
│   ├── Model/service/PORO → Read `references/core.md`
│   ├── Request/controller → Read `references/rails.md`
│   └── System/feature/job/mailer → Read `references/rails.md`
│
├── Using test doubles, stubs, or mocks?
│   └── Read `references/mocks.md`
│
├── Writing custom or complex matchers?
│   └── Read `references/matchers.md`
│
└── Fixing a failing spec?
    ├── Factory-related error → Read `references/factory_bot.md`
    ├── Mock/stub error → Read `references/mocks.md`
    ├── Matcher error → Read `references/matchers.md`
    └── Rails-specific error → Read `references/rails.md`
```

**Need code examples?**

```
├── Basic spec structure, hooks, shared examples
│   └── See `examples/core/`
│
├── Matcher usage patterns
│   └── See `examples/matchers/`
│
├── Test doubles and stubbing
│   └── See `examples/mocks/`
│
├── Rails spec templates (model, request, system, job, mailer)
│   └── See `examples/rails/`
│
└── Factory definitions with traits and associations
    └── See `examples/factory_bot/`
```

### Running Specs

```bash
rspec                           # all specs
rspec spec/models               # directory
rspec spec/user_spec.rb         # file
rspec spec/user_spec.rb:23      # line
rspec --format doc              # documentation format
rspec --only-failures           # re-run failures
rspec --profile 10              # show slowest
```

### Debugging

```bash
rspec --seed 12345              # reproduce random order
rspec --fail-fast               # stop on first failure
rspec --backtrace               # full backtrace
```
Files in this package (55)
  • SKILL.md 10 KB
  • examples/core/basic_structure.rb 1 KB
  • examples/core/configuration.rb 3 KB
  • examples/core/hooks.rb 3 KB
  • examples/core/memoized_helpers.rb 3 KB
  • examples/core/metadata_filtering.rb 3 KB
  • examples/core/shared_examples.rb 3 KB
  • examples/factory_bot/associations.rb 7 KB
  • examples/factory_bot/build_strategies.rb 6 KB
  • examples/factory_bot/callbacks.rb 7 KB
  • examples/factory_bot/custom_construction.rb 7 KB
  • examples/factory_bot/factory_definition.rb 4 KB
  • examples/factory_bot/inheritance.rb 7 KB
  • examples/factory_bot/traits.rb 6 KB
  • examples/factory_bot/transients.rb 5 KB
  • examples/matchers/change.rb 3 KB
  • examples/matchers/collections.rb 4 KB
  • examples/matchers/comparisons.rb 2 KB
  • examples/matchers/composing.rb 4 KB
  • examples/matchers/custom_matchers.rb 4 KB
  • examples/matchers/equality.rb 1 KB
  • examples/matchers/errors.rb 4 KB
  • examples/matchers/output.rb 3 KB
  • examples/matchers/predicates.rb 2 KB
  • examples/matchers/truthiness.rb 2 KB
  • examples/matchers/types.rb 2 KB
  • examples/matchers/yield.rb 4 KB
  • examples/mocks/any_instance.rb 5 KB
  • examples/mocks/argument_matchers.rb 5 KB
  • examples/mocks/constants.rb 5 KB
  • examples/mocks/doubles.rb 4 KB
  • examples/mocks/expectations.rb 4 KB
  • examples/mocks/message_chains.rb 5 KB
  • examples/mocks/ordering.rb 4 KB
  • examples/mocks/receive_counts.rb 4 KB
  • examples/mocks/responses.rb 6 KB
  • examples/mocks/spies.rb 4 KB
  • examples/mocks/stubbing.rb 3 KB
  • examples/rails/channels.rb 6 KB
  • examples/rails/controller_specs.rb 7 KB
  • examples/rails/helper_specs.rb 7 KB
  • examples/rails/job_specs.rb 7 KB
  • examples/rails/mailer_specs.rb 6 KB
  • examples/rails/matchers.rb 9 KB
  • examples/rails/model_specs.rb 5 KB
  • examples/rails/request_specs.rb 7 KB
  • examples/rails/routing_specs.rb 7 KB
  • examples/rails/system_specs.rb 7 KB
  • examples/rails/transactions.rb 6 KB
  • examples/rails/view_specs.rb 6 KB
  • references/core.md 18 KB
  • references/factory_bot.md 12 KB
  • references/matchers.md 10 KB
  • references/mocks.md 8 KB
  • references/rails.md 11 KB

Versions

RepositoryScoreLicence
This page · hoblin/claude-ruby-marketplace100MIT
G1Joshi/Agent-Skills100MIT
aks-builds/quality-skills100MIT
el-feo/ai-context100MIT
tuannv14/claude-team-toolkit98MIT

Database snapshot: 13.11.2026 · package version 40b23e61dcf8 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95rspec-skill
    Generates RSpec tests in Ruby with describe/context/it blocks, matchers, let/before hooks, and mocking. Use when user mentions "RSpec", "describe do", "expect().to", "Ruby test". Triggers on: "RSpec", "expect().to eq()", "describe do", "Ruby test", "spec file".
  • 100tdd
    Test-driven development and testing patterns for Rails applications. Drives implementation from tests using an outside-in approach with RSpec, Capybara, and FactoryBot. Use when building new features, writing or improving tests, adding test coverage, fixing bugs with a…
  • 100rspec-fundamentals
    Use when rSpec fundamentals including describe, context, it blocks, let, and basic matchers for BDD testing.
  • 95rspec-testing
    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…
  • 100rspec-advanced
    Use when advanced RSpec features including custom matchers, shared examples, metadata, and hooks.
  • 100testing-patterns
    Writes Minitest tests with fixtures following 37signals conventions. Uses Minitest (not RSpec) and fixtures (not factories). Use when writing tests, adding test coverage, or creating fixtures. WHEN NOT: For RSpec or FactoryBot patterns (this project uses Minitest + fixtures…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.