๐Ÿงช

RSpec

BDD (Behavior-Driven Development) test framework

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