빠른 참조

RSpec Rails 치트시트

rspec-rails 빠른 참조 가이드: 모델 spec, 요청(request) spec, 시스템 spec, 라우트 spec 및 데이터베이스 트랜잭션.

· 게시일

rspec-rails는 RSpec 테스팅 프레임워크를 Ruby on Rails에 통합합니다.

설치 및 설정

Gemfile에 추가:

group :development, :test do
  gem 'rspec-rails', '~> 6.1.0'
end

spec 디렉터리 초기화:

bin/rails generate rspec:install

모델 Spec (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

요청 Spec (spec/requests/)

Request spec은 전체 HTTP 요청 주기를 테스트합니다:

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

Capybara를 사용한 시스템 Spec

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

참고 자료

관련 주제