빠른 참조

RSpec 치트시트

RSpec 종합 레퍼런스 가이드: Ruby의 BDD 테스팅, describe, context, it, 매처(matchers), let, subject, 목(mocks) 및 스파이(spies).

· 게시일

RSpec은 Ruby를 위한 행위 주도 개발(BDD) 테스팅 도구입니다.

기본 Spec 구조

RSpec.describe Calculator do
  let(:calculator) { Calculator.new }

  describe "#add" do
    context "when adding positive numbers" do
      it "returns the arithmetic sum" do
        expect(calculator.add(2, 3)).to eq(5)
      end
    end

    context "when given invalid input" do
      it "raises an ArgumentError" do
        expect { calculator.add(2, "x") }.to raise_error(ArgumentError)
      end
    end
  end
end

핵심 매처 (Core Matchers)

# 동등성
expect(actual).to eq(expected)       # 값 일치 (==)
expect(actual).to be(expected)       # 객체 동일성 (equal?)

# 참/거짓 및 조건 서술
expect(actual).to be_truthy
expect(actual).to be_nil
expect(user).to be_active            # user.active? 호출

# 컬렉션
expect(list).to include("ruby")
expect(list).to match_array([1, 2])  # 순서에 상관없이 동일한 요소 포함
expect(list).to be_empty

# 비교
expect(value).to be > 10
expect(value).to be_between(1, 100).inclusive

# 예외 및 오류
expect { risky_call }.to raise_error(StandardError, /message/)
expect { safe_call }.not_to raise_error

목과 스텁 (rspec-mocks)

# 메서드 스텁
allow(user).to receive(:name).and_return("Alice")

# 메서드 호출 기대 검증
expect(notifier).to receive(:send_email).with("[email protected]").once

# 목 객체 (Double)
mock_service = double("PaymentService", charge: true)

참고 자료

관련 주제