Skip to content

Instantly share code, notes, and snippets.

@sr
Created May 7, 2009 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sr/108184 to your computer and use it in GitHub Desktop.
Save sr/108184 to your computer and use it in GitHub Desktop.
Crazy test/unit + rack/test hax
require "test/unit"
require "rack/test"
require "contest"
require "sinatra/base"
class MyApp < Sinatra::Base
set :environment, :test
get "/" do
"Hi, #{params["name"]}."
end
get "/with-setup" do
val = $SETUP_VALUE
$SETUP_VALUE = nil
val
end
get "/previous-setup-cleared" do
val = $SETUP_VALUE
$SETUP_VALUE = nil
val
end
end
class Test::Unit::TestCase
class << self
include Test::Unit::Assertions
def get(uri, params={}, env={}, &block)
setup = [once, twice].compact
define_method "test GET #{uri} #{params.inspect} #{env.inspect}" do
setup.each { |fn| fn.call }
session.get(uri, params, env, &block)
end
once(&twice)
twice { } # shift
end
def once(&block)
block_given? ? @once = block : @once
end
def twice(&block)
block_given? ? @twice = block : @twice
end
end
def session
@session ||= Rack::Test::Session.new(MyApp)
end
end
class MyAppTest < Test::Unit::TestCase
get("/", {"name" => "John Doe"}) do |response|
assert response.ok?
assert_equal "Hi, John Doe.", response.body.to_s
end
once { $SETUP_VALUE = 'hello world!' }
get("/with-setup#once-only") do |response|
assert_equal 'hello world!', response.body.to_s
end
get("/previous-setup-cleared") do |response|
assert_equal '', response.body.to_s
end
twice { $SETUP_VALUE = 'hello world again!' }
get("/with-setup#once") do |response|
assert_equal 'hello world again!', response.body.to_s
end
get("/with-setup#twice") do |response|
assert_equal 'hello world again!', response.body.to_s
end
get("/previous-setup-cleared#after-twice") do |response|
assert_equal '', response.body.to_s
end
context "with $SETUP_VALUE set to 'foo'" do
setup do
$SETUP_VALUE = "foo"
end
get "/with-setup" do |response|
assert_equal "foo", response.body.to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment