rspec-rails integrates the RSpec testing framework into Ruby on Rails.
Installation & Setup
Add to Gemfile:
group :development, :test do
gem 'rspec-rails', '~> 6.1.0'
end
Initialize spec directories:
bin/rails generate rspec:install
Model Specs (spec/models/)
require 'rails_helper'
RSpec.describe User, type: :model do
it "is valid with valid attributes" do
user = User.new(name: "Alice", email: "[email protected]")
expect(user).to be_valid
end
it "is invalid without an email" do
user = User.new(name: "Alice", email: nil)
expect(user).not_to be_valid
expect(user.errors[:email]).to include("can't be blank")
end
end
Request Specs (spec/requests/)
Request specs test whole HTTP request cycles:
require 'rails_helper'
RSpec.describe "Articles API", type: :request do
describe "GET /articles" do
it "returns HTTP success and lists articles" do
get "/articles", headers: { "Accept" => "application/json" }
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json).to be_an(Array)
end
end
end
System Specs with Capybara
require 'rails_helper'
RSpec.describe "User Login", type: :system do
before do
driven_by(:selenium_chrome_headless)
end
it "allows user to sign in" do
visit login_path
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "secret123"
click_button "Sign in"
expect(page).to have_content("Welcome back!")
end
end