クイックリファレンス

Rack::Test チートシート

Rack::Test のクイックリファレンス:Ruby Rack、Sinatra、Rails アプリケーション向けの軽量テスト API、HTTP メソッド、レスポンス検証。

· 公開日

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'

参考リンク

関連テーマ