This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Rack::Test Cheatsheet

A quick reference guide for Rack::Test: lightweight testing API for Ruby Rack, Sinatra, and Rails applications.

· Published

Rack::Test is a simple, lightweight testing library for Ruby applications that speak the Rack protocol without starting an HTTP server.

Basic Setup (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 Request Methods

# GET request with query params
get '/search', q: 'ruby'

# POST request with form payload
post '/users', name: 'Alice', email: '[email protected]'

# PUT and DELETE
put '/users/1', status: 'active'
delete '/users/1'

# File upload
post '/upload', file: Rack::Test::UploadedFile.new('spec/fixtures/avatar.png', 'image/png')

Inspecting Responses

last_response.status          # => 200, 404, etc.
last_response.body            # => Response string
last_response.headers         # => Hash of HTTP response headers
last_response.ok?             # => true if 200..299
last_response.redirect?       # => true if 301, 302, 303, 307
last_response.location         # => Redirect destination URL

Setting Headers & Authentication

# Set request header
header 'Accept', 'application/json'

# HTTP Basic Authentication
authorize 'username', 'secretpassword'

References

Related topics