About

What Is RSpec? Writing Rails Tests That Read Like Sentences

The basics of describe, context, it and expect

RSpec is the most widely used test framework for Ruby/Rails.

RSpec.describe Post, type: :model do
  describe 'validations' do
    it 'requires a title' do
      post = Post.new(title: nil)
      expect(post).not_to be_valid
      expect(post.errors[:title]).to include("can't be blank")
    end
  end

  describe '#published?' do
    context 'when status is published' do
      it 'returns true' do
        post = Post.new(status: 'published')
        expect(post.published?).to be true
      end
    end
  end
end

Test types:

  • Model Spec — model logic, validations, associations

  • Request Spec — HTTP request/response (replaces Controller tests)

  • System Spec — browser simulation (Capybara)

  • Mailer Spec — email delivery

  • Job Spec — background jobs

Key Points

1

Add rspec-rails to Gemfile → rails generate rspec:install

2

Write test files in spec/ directory (_spec.rb suffix)

3

Write with describe "target" / context "condition" / it "expected behavior" structure

4

expect(actual).to eq(expected) — verification (matcher)

5

let(:variable) { value } — lazy evaluation variable definition

6

before { setup } — run before each test (setup)

Pros

  • ✓ Good readability with near-natural language syntax
  • ✓ Can test all Rails layers
  • ✓ Rich Matcher library
  • ✓ Large community with abundant resources

Cons

  • ✗ Learning curve (describe/context/it, let, subject, etc.)
  • ✗ Large test suites have long execution times
  • ✗ More complex setup compared to Minitest
  • ✗ Excessive mock/stub leads to fragile tests

Use Cases

Model validation tests API endpoint tests (Request Spec) Service Object unit tests Authentication/authorization tests
← What Are Strong Parameters? Accepting Only the Fields You Allow How to Use FactoryBot to Build Test Data on the Fly →