🌐
Request Specs
HTTP 요청/응답을 테스트하는 통합 테스트
Request Spec은 Controller 테스트를 대체하는 통합 테스트입니다. 실제 HTTP 요청을 시뮬레이션하여 라우팅부터 응답까지 전체 스택을 테스트합니다.
RSpec.describe 'Posts', type: :request do
let(:user) { create(:user) }
let(:post_record) { create(:post, user: user) }
describe 'GET /posts' do
it '목록을 반환한다' do
get posts_path
expect(response).to have_http_status(:success)
end
end
describe 'POST /posts' do
context '로그인 상태' do
before { sign_in user } # Devise 헬퍼
it '새 포스트를 생성한다' do
expect {
post posts_path, params: { post: { title: '제목', content: '내용' } }
}.to change(Post, :count).by(1)
expect(response).to redirect_to(post_path(Post.last))
end
end
context '미로그인 상태' do
it '로그인 페이지로 리다이렉트' do
post posts_path, params: { post: { title: '제목' } }
expect(response).to redirect_to(new_user_session_path)
end
end
end
end
핵심 포인트
1
spec/requests/ 디렉토리에 스펙 파일 생성
2
get/post/patch/delete 메서드로 HTTP 요청 시뮬레이션
3
params: 옵션으로 요청 파라미터 전달
4
headers: 옵션으로 요청 헤더 설정 (Turbo Stream 등)
5
expect(response).to have_http_status(:success) — 상태 코드 검증
6
expect { action }.to change(Model, :count) — 데이터 변경 검증
장점
- ✓ 실제 HTTP 요청 시뮬레이션 — 현실적인 테스트
- ✓ 라우팅부터 응답까지 전체 스택 검증
- ✓ Controller + View 통합 테스트
- ✓ Devise 등 미들웨어와의 상호작용 테스트
단점
- ✗ 단위 테스트보다 느림
- ✗ 실패 시 원인 추적이 복잡할 수 있음
- ✗ 뷰 렌더링 포함으로 테스트 시간 증가
- ✗ 세밀한 Controller 로직 테스트에는 부적합
사용 사례
CRUD 엔드포인트 테스트
인증/권한 테스트
Turbo Stream 응답 테스트
API 응답 검증