Rack::Test는 HTTP 서버를 실행하지 않고도 Rack 프로토콜을 구현한 Ruby 애플리케이션을 테스트할 수 있는 가볍고 단순한 라이브러리입니다.
기본 설정 (RSpec / Minitest)
require 'rack/test'
class AppTest < Minitest::Test
include Rack::Test::Methods
def app
MySinatraApp
end
def test_homepage
get '/'
assert last_response.ok?
assert_equal 'Hello World', last_response.body
end
end
HTTP 요청 메서드
# 쿼리 매개변수가 포함된 GET 요청
get '/search', q: 'ruby'
# 폼 데이터가 포함된 POST 요청
post '/users', name: 'Alice', email: '[email protected]'
# PUT 및 DELETE
put '/users/1', status: 'active'
delete '/users/1'
# 파일 업로드
post '/upload', file: Rack::Test::UploadedFile.new('spec/fixtures/avatar.png', 'image/png')
응답 검사
last_response.status # => 200, 404 등
last_response.body # => 응답 본문 문자열
last_response.headers # => HTTP 응답 헤더 Hash
last_response.ok? # => 200..299 상태 코드일 때 true
last_response.redirect? # => 301, 302, 303, 307 리다이렉트일 때 true
last_response.location # => 리다이렉션 대상 URL
헤더 설정 및 인증
# 요청 헤더 설정
header 'Accept', 'application/json'
# HTTP 기본 인증 (Basic Auth)
authorize 'username', 'secretpassword'