How to Use RSpec in Rails: Setup and Basic Testing
To use
RSpec in Rails, add the rspec-rails gem to your Gemfile, run bundle install, then generate the RSpec files with rails generate rspec:install. Write tests in the spec/ folder using describe and it blocks, then run tests with bundle exec rspec.Syntax
RSpec uses describe blocks to group tests and it blocks to define individual test cases. Inside it, you write expectations using expect() to check your code's behavior.
- describe: Groups related tests, usually for a class or method.
- it: Defines a single test example describing expected behavior.
- expect: Sets an expectation that your code should meet.
ruby
describe 'Calculator' do it 'adds two numbers' do result = 2 + 3 expect(result).to eq(5) end end
Example
This example shows a simple RSpec test for a Rails model Article. It tests that an article is valid with a title and invalid without one.
ruby
require 'rails_helper' RSpec.describe Article, type: :model do it 'is valid with a title' do article = Article.new(title: 'Hello World') expect(article).to be_valid end it 'is invalid without a title' do article = Article.new(title: nil) expect(article).not_to be_valid end end
Output
...
Finished in 0.12345 seconds (files took 1.23 seconds to load)
2 examples, 0 failures
Common Pitfalls
Common mistakes include not running rails generate rspec:install after adding the gem, writing tests outside the spec/ folder, or forgetting to use expect for assertions. Also, mixing test frameworks like Minitest and RSpec can cause confusion.
Always run tests with bundle exec rspec to ensure the correct environment.
ruby
## Wrong: Missing expect it 'adds numbers' do sum = 2 + 2 sum == 4 end ## Right: it 'adds numbers' do sum = 2 + 2 expect(sum).to eq(4) end
Quick Reference
- Add
gem 'rspec-rails'to Gemfile and runbundle install. - Run
rails generate rspec:installto set up. - Write tests in
spec/usingdescribeandit. - Run tests with
bundle exec rspec. - Use
expect(actual).to matcher(expected)for assertions.
Key Takeaways
Add and install the rspec-rails gem, then generate RSpec files with rails generate rspec:install.
Write tests inside spec/ using describe and it blocks with expect for assertions.
Run tests using bundle exec rspec to ensure proper environment and dependencies.
Avoid forgetting expect statements or mixing test frameworks to prevent errors.
Use the quick reference steps to set up and run RSpec tests efficiently in Rails.