Published on October 03, 2025 21:47
1 min read
Michel Sánchez Montells
Featured

Introduction to Test-Driven Development (TDD) with RSpec

Learn the fundamentals of TDD and how to implement it effectively in your Ruby on Rails projects using RSpec and FactoryBot.

Ruby on Rails TDD Testing RSpec Best Practices
Share: Twitter LinkedIn

What is TDD?

Test-Driven Development (TDD) is a software development methodology that inverts the traditional programming process. Instead of writing code and then testing it, TDD proposes writing tests first.

The Red-Green-Refactor Cycle

TDD follows a simple but powerful cycle:

  1. Red: Write a failing test
  2. Green: Write minimal code to make the test pass
  3. Refactor: Improve the code while keeping tests green

Setting up RSpec in Rails

To get started with TDD in Rails, we need to configure RSpec:

# Gemfile
group :development, :test do
  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'shoulda-matchers'
end

Practical Example

Let's see an example of how to implement TDD for a User model:

# spec/models/user_spec.rb
RSpec.describe User, type: :model do
  describe 'validations' do
    it 'requires an email' do
      user = User.new(email: nil)
      expect(user).not_to be_valid
      expect(user.errors[:email]).to include("can't be blank")
    end
  end
end

"TDD is not about testing, it's about design. Tests are just a beneficial side effect."

Benefits of TDD

  • Better code design
  • Greater confidence in changes
  • Living documentation of behavior
  • Fewer bugs in production

Table of Contents

About the Author

MS

Michel Sánchez Montells

Full-Stack Software Developer | Ruby on Rails Expert | TDD Advocate

Full-Stack Developer specialized in Ruby on Rails with over 8 years of experience. Passionate about TDD and development best practices.