Rails TDD Standards
БесплатноБез исполняемых скриптовНе проверенRSpec testing standards and best practices for Rails applications. Use when writing new tests, reviewing test quality, debugging factory errors, setting up…
от djc00p1 241 установка в других каталогахОб этом скилле
Rails TDD Standards
Best practices for writing clean, reliable RSpec tests in Rails applications.
Core Principle: Single Expectation
One assertion per test. Tests should read like specifications — each it block verifies exactly one thing.
# ✅ Correct
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to belong_to(:user) }
# ❌ Wrong — too many expectations in one test
it "validates the user" do
expect(user).to validate_presence_of(:email)
expect(user).to validate_presence_of(:name)
expect(user).to be_valid
end
FactoryBot Patterns
Always use role traits
# ✅ Correct
create(:user, :admin)
create(:user, :member)
create(:user, :guest)
# ❌ Wrong — missing role context
create(:user)
Association keys matter
Check your factory definitions carefully. Wrong keys cause silent failures.
# ✅ Example — if your factory uses owner:
create(:profile, owner: user)
# ❌ Wrong key
create(:profile, user: user) # fails if factory expects owner:
Always set required associations
When a model requires a specific association to be valid, always set it explicitly — don't rely on factory defaults when they might be nil or wrong.
# ✅ Explicit — clear intent, no surprises
let(:record) do
create(:model, required_association: other_record)
end
# ❌ Implicit — may break if factory default changes
let(:record) { create(:model) }
Use described_class not hardcoded class names
# ✅
subject { described_class.new(params) }
# ❌
subject { MyService.new(params) }
Common FactoryBot Gotchas
Join tables without primary key
Tables with id: false can't use .last or .first.
# ✅ Use a scoped query
record = JoinModel.find_by(field_a: a, field_b: b)
# ❌ Will raise ActiveRecord::MissingRequiredOrderError
record = JoinModel.last
RecordInvalid from missing role/trait
If you see Validation failed: X must have Y role — you're missing a trait on the user factory.
# ✅
user = create(:user, :editor)
# ❌ causes "must be an editor" validation error
user = create(:user)
Spec Structure
RSpec.describe MyClass do
# Subject
subject(:instance) { described_class.new(params) }
# Shared setup
let(:user) { create(:user, :admin) }
# Group by behavior
describe "#method_name" do
context "when condition is true" do
it "does the expected thing" do
expect(instance.method_name).to eq(expected)
end
end
context "when condition is false" do
it "does something else" do
expect(instance.method_name).to be_nil
end
end
end
end
Mocking & Stubbing
# Stub a method
allow(object).to receive(:method_name).and_return(value)
# Stub and verify it was called
expect(object).to receive(:method_name).once
# Stub HTTP calls (WebMock)
stub_request(:post, "https://api.example.com/endpoint")
.to_return(status: 200, body: { result: "ok" }.to_json)
# Allow localhost for system tests (if using WebMock)
WebMock.disable_net_connect!(allow_localhost: true)
Service Object Testing
RSpec.describe MyService do
describe "#call" do
context "with valid params" do
it "returns the expected result" do
result = described_class.new(valid_params).call
expect(result).to be_a(ExpectedClass)
end
it "creates the expected record" do
expect { described_class.new(valid_params).call }
.to change(Record, :count).by(1)
end
end
context "with invalid params" do
it "returns false" do
expect(described_class.new(invalid_params).call).to be(false)
end
end
end
end
Rails 8 Spec Compatibility
Rails 8 changed two controller-side APIs that specs interact with - strong
parameters and CSRF behavior. What changed, and how to spec it, is in
references/rails-8-controller-gotchas.md.
CI Database Setup
Critical: Never use db:prepare in CI. It runs seeds, which pollutes the test database and causes scoped queries to return unexpected results.
# ✅ CI config (GitHub Actions / etc.)
- run: bundle exec rails db:schema:load RAILS_ENV=test
# ❌ Runs seeds → pollutes test DB → scope specs fail
- run: bundle exec rails db:prepare RAILS_ENV=test
If you see scope specs randomly returning too many records, check your CI DB setup first. Seeds belong in development, not the test environment.
Callback Testing: before_create vs before_validation
before_create callbacks are skipped by FactoryBot's build(). If your callback needs to fire during build (e.g., for token generation, slug assignment), use before_validation on: :create instead.
# ✅ Works with both build() and create()
before_validation :generate_token, on: :create
# ❌ Skipped by build() — token will be nil in specs using build
before_create :generate_token
This is especially important for:
- Token generation (API keys, one-time tokens)
- Slug genera
Установить Rails TDD Standards в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Rails TDD Standards?
RSpec testing standards and best practices for Rails applications. Use when writing new tests, reviewing test quality, debugging factory errors, setting up FactoryBot, or enforcing single-expectation patterns. Also use when a test fails due to factory misconfiguration, wrong association keys, or missing role traits. Triggers on phrases like "write a test", "add specs", "factory error", "test is failing", "how should I test this", or when reviewing test code in a Rails project.
Как установить скилл Rails TDD Standards?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Rails TDD Standards запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic