First pass at block styles for tests

TODO:
* test/routing_test.rb
* test/settings_test.rb
This commit is contained in:
Zachary Scott 2012-05-21 17:21:59 -04:00
parent cab56ed7d6
commit 46e8bd67b3
33 changed files with 611 additions and 708 deletions

View File

@ -7,9 +7,7 @@ class BaseTest < Test::Unit::TestCase
describe 'Sinatra::Base subclasses' do describe 'Sinatra::Base subclasses' do
class TestApp < Sinatra::Base class TestApp < Sinatra::Base
get '/' do get('/') { 'Hello World' }
'Hello World'
end
end end
it 'include Rack::Utils' do it 'include Rack::Utils' do
@ -99,9 +97,7 @@ class BaseTest < Test::Unit::TestCase
super super
end end
get '/' do get('/') { 'Hello from middleware' }
'Hello from middleware'
end
end end
middleware = TestMiddleware.new(app) middleware = TestMiddleware.new(app)
@ -125,9 +121,7 @@ class BaseTest < Test::Unit::TestCase
end end
class TestMiddleware < Sinatra::Base class TestMiddleware < Sinatra::Base
get '/low-level-forward' do get('/low-level-forward') { app.call(env) }
app.call(env)
end
end end
it 'can call the downstream app directly and return result' do it 'can call the downstream app directly and return result' do

View File

@ -5,11 +5,11 @@ require 'builder'
class BuilderTest < Test::Unit::TestCase class BuilderTest < Test::Unit::TestCase
def builder_app(options = {}, &block) def builder_app(options = {}, &block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set options set options
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -43,49 +43,45 @@ class BuilderTest < Test::Unit::TestCase
end end
it 'renders inline blocks' do it 'renders inline blocks' do
builder_app { builder_app do
@name = "Frank & Mary" @name = "Frank & Mary"
builder do |xml| builder { |xml| xml.couple @name }
xml.couple @name end
end
}
assert ok? assert ok?
assert_equal "<couple>Frank &amp; Mary</couple>\n", body assert_equal "<couple>Frank &amp; Mary</couple>\n", body
end end
it 'renders .builder files in views path' do it 'renders .builder files in views path' do
builder_app { builder_app do
@name = "Blue" @name = "Blue"
builder :hello builder :hello
} end
assert ok? assert ok?
assert_equal %(<exclaim>You're my boy, Blue!</exclaim>\n), body assert_equal %(<exclaim>You're my boy, Blue!</exclaim>\n), body
end end
it "renders with inline layouts" do it "renders with inline layouts" do
mock_app { mock_app do
layout do layout { %(xml.layout { xml << yield }) }
%(xml.layout { xml << yield })
end
get('/') { builder %(xml.em 'Hello World') } get('/') { builder %(xml.em 'Hello World') }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body
end end
it "renders with file layouts" do it "renders with file layouts" do
builder_app { builder_app do
builder %(xml.em 'Hello World'), :layout => :layout2 builder %(xml.em 'Hello World'), :layout => :layout2
} end
assert ok? assert ok?
assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app do
get('/') { builder :no_such_template } get('/') { builder :no_such_template }
} end
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
end end

View File

@ -12,11 +12,11 @@ end
class CoffeeTest < Test::Unit::TestCase class CoffeeTest < Test::Unit::TestCase
def coffee_app(options = {}, &block) def coffee_app(options = {}, &block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set(options) set(options)
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -77,9 +77,7 @@ class CoffeeTest < Test::Unit::TestCase
it "passes default coffee options to the coffee engine" do it "passes default coffee options to the coffee engine" do
mock_app do mock_app do
set :coffee, :no_wrap => true # default coffee style is :nested set :coffee, :no_wrap => true # default coffee style is :nested
get '/' do get('/') { coffee "alert 'Aye!'\n" }
coffee "alert 'Aye!'\n"
end
end end
get '/' get '/'
assert ok? assert ok?

View File

@ -7,7 +7,7 @@ class CreoleTest < Test::Unit::TestCase
def creole_app(&block) def creole_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -40,7 +40,9 @@ class CreoleTest < Test::Unit::TestCase
end end
it "renders with file layouts" do it "renders with file layouts" do
creole_app { creole 'Hello World', :layout => :layout2, :layout_engine => :erb } creole_app do
creole 'Hello World', :layout => :layout2, :layout_engine => :erb
end
assert ok? assert ok?
assert_body "ERB Layout!\n<p>Hello World</p>" assert_body "ERB Layout!\n<p>Hello World</p>"
end end
@ -49,9 +51,7 @@ class CreoleTest < Test::Unit::TestCase
mock_app do mock_app do
template(:inner) { "hi" } template(:inner) { "hi" }
template(:outer) { "<outer><%= creole :inner %></outer>" } template(:outer) { "<outer><%= creole :inner %></outer>" }
get '/' do get('/') { erb :outer }
erb :outer
end
end end
get '/' get '/'

View File

@ -63,9 +63,7 @@ class DelegatorTest < Test::Unit::TestCase
%w[get put post delete options patch].each do |verb| %w[get put post delete options patch].each do |verb|
it "delegates #{verb} correctly" do it "delegates #{verb} correctly" do
delegation_app do delegation_app do
send verb, '/hello' do send(verb, '/hello') { 'Hello World' }
'Hello World'
end
end end
request = Rack::MockRequest.new(@app) request = Rack::MockRequest.new(@app)

View File

@ -11,10 +11,10 @@ class ERBTest < Test::Unit::TestCase
end end
def erb_app(&block) def erb_app(&block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -35,57 +35,51 @@ class ERBTest < Test::Unit::TestCase
end end
it 'takes a :locals option' do it 'takes a :locals option' do
erb_app { erb_app do
locals = {:foo => 'Bar'} locals = {:foo => 'Bar'}
erb '<%= foo %>', :locals => locals erb '<%= foo %>', :locals => locals
} end
assert ok? assert ok?
assert_equal 'Bar', body assert_equal 'Bar', body
end end
it "renders with inline layouts" do it "renders with inline layouts" do
mock_app { mock_app do
layout { 'THIS. IS. <%= yield.upcase %>!' } layout { 'THIS. IS. <%= yield.upcase %>!' }
get('/') { erb 'Sparta' } get('/') { erb 'Sparta' }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal 'THIS. IS. SPARTA!', body assert_equal 'THIS. IS. SPARTA!', body
end end
it "renders with file layouts" do it "renders with file layouts" do
erb_app { erb_app { erb 'Hello World', :layout => :layout2 }
erb 'Hello World', :layout => :layout2
}
assert ok? assert ok?
assert_body "ERB Layout!\nHello World" assert_body "ERB Layout!\nHello World"
end end
it "renders erb with blocks" do it "renders erb with blocks" do
mock_app { mock_app do
def container def container
@_out_buf << "THIS." @_out_buf << "THIS."
yield yield
@_out_buf << "SPARTA!" @_out_buf << "SPARTA!"
end end
def is; "IS." end def is; "IS." end
get '/' do get('/') { erb '<% container do %> <%= is %> <% end %>' }
erb '<% container do %> <%= is %> <% end %>' end
end
}
get '/' get '/'
assert ok? assert ok?
assert_equal 'THIS. IS. SPARTA!', body assert_equal 'THIS. IS. SPARTA!', body
end end
it "can be used in a nested fashion for partials and whatnot" do it "can be used in a nested fashion for partials and whatnot" do
mock_app { mock_app do
template(:inner) { "<inner><%= 'hi' %></inner>" } template(:inner) { "<inner><%= 'hi' %></inner>" }
template(:outer) { "<outer><%= erb :inner %></outer>" } template(:outer) { "<outer><%= erb :inner %></outer>" }
get '/' do get('/') { erb :outer }
erb :outer end
end
}
get '/' get '/'
assert ok? assert ok?

View File

@ -42,9 +42,7 @@ class ExtensionsTest < Test::Unit::TestCase
end end
it 'allows extending by passing a block' do it 'allows extending by passing a block' do
Sinatra::Base.register { Sinatra::Base.register { def im_in_ur_anonymous_module; end }
def im_in_ur_anonymous_module; end
}
assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module) assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module)
end end

View File

@ -5,14 +5,14 @@ class BeforeFilterTest < Test::Unit::TestCase
count = 0 count = 0
mock_app do mock_app do
get('/') { 'Hello World' } get('/') { 'Hello World' }
before { before do
assert_equal 0, count assert_equal 0, count
count = 1 count = 1
} end
before { before do
assert_equal 1, count assert_equal 1, count
count = 2 count = 2
} end
end end
get '/' get '/'
@ -22,11 +22,11 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "can modify the request" do it "can modify the request" do
mock_app { mock_app do
get('/foo') { 'foo' } get('/foo') { 'foo' }
get('/bar') { 'bar' } get('/bar') { 'bar' }
before { request.path_info = '/bar' } before { request.path_info = '/bar' }
} end
get '/foo' get '/foo'
assert ok? assert ok?
@ -34,10 +34,10 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "can modify instance variables available to routes" do it "can modify instance variables available to routes" do
mock_app { mock_app do
before { @foo = 'bar' } before { @foo = 'bar' }
get('/foo') { @foo } get('/foo') { @foo }
} end
get '/foo' get '/foo'
assert ok? assert ok?
@ -45,13 +45,13 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "allows redirects" do it "allows redirects" do
mock_app { mock_app do
before { redirect '/bar' } before { redirect '/bar' }
get('/foo') do get('/foo') do
fail 'before block should have halted processing' fail 'before block should have halted processing'
'ORLY?!' 'ORLY?!'
end end
} end
get '/foo' get '/foo'
assert redirect? assert redirect?
@ -60,13 +60,13 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "does not modify the response with its return value" do it "does not modify the response with its return value" do
mock_app { mock_app do
before { 'Hello World!' } before { 'Hello World!' }
get '/foo' do get('/foo') do
assert_equal [], response.body assert_equal [], response.body
'cool' 'cool'
end end
} end
get '/foo' get '/foo'
assert ok? assert ok?
@ -74,12 +74,12 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "does modify the response with halt" do it "does modify the response with halt" do
mock_app { mock_app do
before { halt 302, 'Hi' } before { halt 302, 'Hi' }
get '/foo' do get '/foo' do
"should not happen" "should not happen"
end end
} end
get '/foo' get '/foo'
assert_equal 302, response.status assert_equal 302, response.status
@ -87,10 +87,10 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "gives you access to params" do it "gives you access to params" do
mock_app { mock_app do
before { @foo = params['foo'] } before { @foo = params['foo'] }
get('/foo') { @foo } get('/foo') { @foo }
} end
get '/foo?foo=cool' get '/foo?foo=cool'
assert ok? assert ok?
@ -98,10 +98,10 @@ class BeforeFilterTest < Test::Unit::TestCase
end end
it "properly unescapes parameters" do it "properly unescapes parameters" do
mock_app { mock_app do
before { @foo = params['foo'] } before { @foo = params['foo'] }
get('/foo') { @foo } get('/foo') { @foo }
} end
get '/foo?foo=bar%3Abaz%2Fbend' get '/foo?foo=bar%3Abaz%2Fbend'
assert ok? assert ok?
@ -112,9 +112,7 @@ class BeforeFilterTest < Test::Unit::TestCase
base = Class.new(Sinatra::Base) base = Class.new(Sinatra::Base)
base.before { @foo = 'hello from superclass' } base.before { @foo = 'hello from superclass' }
mock_app(base) { mock_app(base) { get('/foo') { @foo } }
get('/foo') { @foo }
}
get '/foo' get '/foo'
assert_equal 'hello from superclass', body assert_equal 'hello from superclass', body
@ -122,11 +120,11 @@ class BeforeFilterTest < Test::Unit::TestCase
it 'does not run before filter when serving static files' do it 'does not run before filter when serving static files' do
ran_filter = false ran_filter = false
mock_app { mock_app do
before { ran_filter = true } before { ran_filter = true }
set :static, true set :static, true
set :public_folder, File.dirname(__FILE__) set :public_folder, File.dirname(__FILE__)
} end
get "/#{File.basename(__FILE__)}" get "/#{File.basename(__FILE__)}"
assert ok? assert ok?
assert_equal File.read(__FILE__), body assert_equal File.read(__FILE__), body
@ -176,14 +174,14 @@ class AfterFilterTest < Test::Unit::TestCase
count = 0 count = 0
mock_app do mock_app do
get('/') { 'Hello World' } get('/') { 'Hello World' }
after { after do
assert_equal 0, count assert_equal 0, count
count = 1 count = 1
} end
after { after do
assert_equal 1, count assert_equal 1, count
count = 2 count = 2
} end
end end
get '/' get '/'
@ -193,10 +191,10 @@ class AfterFilterTest < Test::Unit::TestCase
end end
it "allows redirects" do it "allows redirects" do
mock_app { mock_app do
get('/foo') { 'ORLY' } get('/foo') { 'ORLY' }
after { redirect '/bar' } after { redirect '/bar' }
} end
get '/foo' get '/foo'
assert redirect? assert redirect?
@ -205,10 +203,10 @@ class AfterFilterTest < Test::Unit::TestCase
end end
it "does not modify the response with its return value" do it "does not modify the response with its return value" do
mock_app { mock_app do
get('/foo') { 'cool' } get('/foo') { 'cool' }
after { 'Hello World!' } after { 'Hello World!' }
} end
get '/foo' get '/foo'
assert ok? assert ok?
@ -216,12 +214,12 @@ class AfterFilterTest < Test::Unit::TestCase
end end
it "does modify the response with halt" do it "does modify the response with halt" do
mock_app { mock_app do
get '/foo' do get '/foo' do
"should not be returned" "should not be returned"
end end
after { halt 302, 'Hi' } after { halt 302, 'Hi' }
} end
get '/foo' get '/foo'
assert_equal 302, response.status assert_equal 302, response.status
@ -245,11 +243,11 @@ class AfterFilterTest < Test::Unit::TestCase
it 'does not run after filter when serving static files' do it 'does not run after filter when serving static files' do
ran_filter = false ran_filter = false
mock_app { mock_app do
after { ran_filter = true } after { ran_filter = true }
set :static, true set :static, true
set :public_folder, File.dirname(__FILE__) set :public_folder, File.dirname(__FILE__)
} end
get "/#{File.basename(__FILE__)}" get "/#{File.basename(__FILE__)}"
assert ok? assert ok?
assert_equal File.read(__FILE__), body assert_equal File.read(__FILE__), body
@ -308,9 +306,9 @@ class AfterFilterTest < Test::Unit::TestCase
before(:host_name => 'example.com') { ran = true } before(:host_name => 'example.com') { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_HOST' => 'example.org' } get('/', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran assert !ran
get '/', {}, { 'HTTP_HOST' => 'example.com' } get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert ran assert ran
end end
@ -320,11 +318,11 @@ class AfterFilterTest < Test::Unit::TestCase
before('/foo', :host_name => 'example.com') { ran = true } before('/foo', :host_name => 'example.com') { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_HOST' => 'example.com' } get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_HOST' => 'example.org' } get('/foo', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_HOST' => 'example.com' } get('/foo', {}, { 'HTTP_HOST' => 'example.com' })
assert ran assert ran
end end
@ -334,9 +332,9 @@ class AfterFilterTest < Test::Unit::TestCase
after(:host_name => 'example.com') { ran = true } after(:host_name => 'example.com') { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_HOST' => 'example.org' } get('/', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran assert !ran
get '/', {}, { 'HTTP_HOST' => 'example.com' } get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert ran assert ran
end end
@ -346,11 +344,11 @@ class AfterFilterTest < Test::Unit::TestCase
after('/foo', :host_name => 'example.com') { ran = true } after('/foo', :host_name => 'example.com') { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_HOST' => 'example.com' } get('/', {}, { 'HTTP_HOST' => 'example.com' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_HOST' => 'example.org' } get('/foo', {}, { 'HTTP_HOST' => 'example.org' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_HOST' => 'example.com' } get('/foo', {}, { 'HTTP_HOST' => 'example.com' })
assert ran assert ran
end end
@ -360,9 +358,9 @@ class AfterFilterTest < Test::Unit::TestCase
before(:user_agent => /foo/) { ran = true } before(:user_agent => /foo/) { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_USER_AGENT' => 'bar' } get('/', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran assert !ran
get '/', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran assert ran
end end
@ -372,11 +370,11 @@ class AfterFilterTest < Test::Unit::TestCase
before('/foo', :user_agent => /foo/) { ran = true } before('/foo', :user_agent => /foo/) { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_USER_AGENT' => 'bar' } get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran assert ran
end end
@ -406,9 +404,9 @@ class AfterFilterTest < Test::Unit::TestCase
after(:user_agent => /foo/) { ran = true } after(:user_agent => /foo/) { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_USER_AGENT' => 'bar' } get('/', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran assert !ran
get '/', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran assert ran
end end
@ -418,11 +416,11 @@ class AfterFilterTest < Test::Unit::TestCase
after('/foo', :user_agent => /foo/) { ran = true } after('/foo', :user_agent => /foo/) { ran = true }
get('/') { 'welcome' } get('/') { 'welcome' }
end end
get '/', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_USER_AGENT' => 'bar' } get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' })
assert !ran assert !ran
get '/foo', {}, { 'HTTP_USER_AGENT' => 'foo' } get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' })
assert ran assert ran
end end
@ -433,7 +431,7 @@ class AfterFilterTest < Test::Unit::TestCase
get('/') { @type } get('/') { @type }
end end
get '/', {}, { 'HTTP_ACCEPT' => '*' } get('/', {}, { 'HTTP_ACCEPT' => '*' })
assert_body 'txt' assert_body 'txt'
end end
end end

View File

@ -5,10 +5,10 @@ require 'haml'
class HAMLTest < Test::Unit::TestCase class HAMLTest < Test::Unit::TestCase
def haml_app(&block) def haml_app(&block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -25,35 +25,29 @@ class HAMLTest < Test::Unit::TestCase
end end
it "renders with inline layouts" do it "renders with inline layouts" do
mock_app { mock_app do
layout { %q(%h1= 'THIS. IS. ' + yield.upcase) } layout { %q(%h1= 'THIS. IS. ' + yield.upcase) }
get('/') { haml '%em Sparta' } get('/') { haml '%em Sparta' }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>\n", body assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>\n", body
end end
it "renders with file layouts" do it "renders with file layouts" do
haml_app { haml_app { haml 'Hello World', :layout => :layout2 }
haml 'Hello World', :layout => :layout2
}
assert ok? assert ok?
assert_equal "<h1>HAML Layout!</h1>\n<p>Hello World</p>\n", body assert_equal "<h1>HAML Layout!</h1>\n<p>Hello World</p>\n", body
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app { get('/') { haml :no_such_template } }
get('/') { haml :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
it "passes HAML options to the Haml engine" do it "passes HAML options to the Haml engine" do
mock_app { mock_app {
get '/' do get('/') { haml "!!!\n%h1 Hello World", :format => :html5 }
haml "!!!\n%h1 Hello World", :format => :html5
end
} }
get '/' get '/'
assert ok? assert ok?
@ -61,27 +55,23 @@ class HAMLTest < Test::Unit::TestCase
end end
it "passes default HAML options to the Haml engine" do it "passes default HAML options to the Haml engine" do
mock_app { mock_app do
set :haml, {:format => :html5} set :haml, {:format => :html5}
get '/' do get('/') { haml "!!!\n%h1 Hello World" }
haml "!!!\n%h1 Hello World" end
end
}
get '/' get '/'
assert ok? assert ok?
assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body
end end
it "merges the default HAML options with the overrides and passes them to the Haml engine" do it "merges the default HAML options with the overrides and passes them to the Haml engine" do
mock_app { mock_app do
set :haml, {:format => :html5, :attr_wrapper => '"'} # default HAML attr are <tag attr='single-quoted'> set :haml, {:format => :html5, :attr_wrapper => '"'} # default HAML attr are <tag attr='single-quoted'>
get '/' do get('/') { haml "!!!\n%h1{:class => :header} Hello World" }
haml "!!!\n%h1{:class => :header} Hello World" get('/html4') {
end
get '/html4' do
haml "!!!\n%h1{:class => 'header'} Hello World", :format => :html4 haml "!!!\n%h1{:class => 'header'} Hello World", :format => :html4
end }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "<!DOCTYPE html>\n<h1 class=\"header\">Hello World</h1>\n", body assert_equal "<!DOCTYPE html>\n<h1 class=\"header\">Hello World</h1>\n", body

File diff suppressed because it is too large Load Diff

View File

@ -5,22 +5,26 @@ require 'less'
class LessTest < Test::Unit::TestCase class LessTest < Test::Unit::TestCase
def less_app(options = {}, &block) def less_app(options = {}, &block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set options set options
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
it 'renders inline Less strings' do it 'renders inline Less strings' do
less_app { less "@white_color: #fff; #main { background-color: @white_color }" } less_app {
less "@white_color: #fff; #main { background-color: @white_color }"
}
assert ok? assert ok?
assert_equal "#main{background-color:#ffffff;}", body.gsub(/\s/, "") assert_equal "#main{background-color:#ffffff;}", body.gsub(/\s/, "")
end end
it 'defaults content type to css' do it 'defaults content type to css' do
less_app { less "@white_color: #fff; #main { background-color: @white_color }" } less_app {
less "@white_color: #fff; #main { background-color: @white_color }"
}
assert ok? assert ok?
assert_equal "text/css;charset=utf-8", response['Content-Type'] assert_equal "text/css;charset=utf-8", response['Content-Type']
end end
@ -55,9 +59,7 @@ class LessTest < Test::Unit::TestCase
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app { get('/') { less :no_such_template } }
get('/') { less :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
end end

View File

@ -7,7 +7,7 @@ class LiquidTest < Test::Unit::TestCase
def liquid_app(&block) def liquid_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -46,9 +46,9 @@ class LiquidTest < Test::Unit::TestCase
end end
it "allows passing locals" do it "allows passing locals" do
liquid_app do liquid_app {
liquid '{{ value }}', :locals => { :value => 'foo' } liquid '{{ value }}', :locals => { :value => 'foo' }
end }
assert ok? assert ok?
assert_equal 'foo', body assert_equal 'foo', body
end end

View File

@ -28,13 +28,11 @@ class MappedErrorTest < Test::Unit::TestCase
describe 'Exception Mappings' do describe 'Exception Mappings' do
it 'invokes handlers registered with ::error when raised' do it 'invokes handlers registered with ::error when raised' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(FooError) { 'Foo!' } error(FooError) { 'Foo!' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 500, status assert_equal 500, status
assert_equal 'Foo!', body assert_equal 'Foo!', body
@ -50,13 +48,11 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it 'uses the Exception handler if no matching handler found' do it 'uses the Exception handler if no matching handler found' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(Exception) { 'Exception!' } error(Exception) { 'Exception!' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 500, status assert_equal 500, status
@ -64,13 +60,11 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it 'walks down inheritance chain for errors' do it 'walks down inheritance chain for errors' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(RuntimeError) { 'Exception!' } error(RuntimeError) { 'Exception!' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 500, status assert_equal 500, status
@ -78,15 +72,13 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it 'favors subclass handler over superclass handler if available' do it 'favors subclass handler over superclass handler if available' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(Exception) { 'Exception!' } error(Exception) { 'Exception!' }
error(FooError) { 'FooError!' } error(FooError) { 'FooError!' }
error(RuntimeError) { 'Exception!' } error(RuntimeError) { 'Exception!' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 500, status assert_equal 500, status
@ -94,68 +86,58 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it "sets env['sinatra.error'] to the rescued exception" do it "sets env['sinatra.error'] to the rescued exception" do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(FooError) { error(FooError) do
assert env.include?('sinatra.error') assert env.include?('sinatra.error')
assert env['sinatra.error'].kind_of?(FooError) assert env['sinatra.error'].kind_of?(FooError)
'looks good' 'looks good'
}
get '/' do
raise FooError
end end
} get('/') { raise FooError }
end
get '/' get '/'
assert_equal 'looks good', body assert_equal 'looks good', body
end end
it "raises errors from the app when raise_errors set and no handler defined" do it "raises errors from the app when raise_errors set and no handler defined" do
mock_app { mock_app do
set :raise_errors, true set :raise_errors, true
get '/' do get('/') { raise FooError }
raise FooError end
end
}
assert_raise(FooError) { get '/' } assert_raise(FooError) { get '/' }
end end
it "calls error handlers before raising errors even when raise_errors is set" do it "calls error handlers before raising errors even when raise_errors is set" do
mock_app { mock_app do
set :raise_errors, true set :raise_errors, true
error(FooError) { "she's there." } error(FooError) { "she's there." }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
assert_nothing_raised { get '/' } assert_nothing_raised { get '/' }
assert_equal 500, status assert_equal 500, status
end end
it "never raises Sinatra::NotFound beyond the application" do it "never raises Sinatra::NotFound beyond the application" do
mock_app(Sinatra::Application) { get('/') { raise Sinatra::NotFound }} mock_app(Sinatra::Application) do
get('/') { raise Sinatra::NotFound }
end
assert_nothing_raised { get '/' } assert_nothing_raised { get '/' }
assert_equal 404, status assert_equal 404, status
end end
it "cascades for subclasses of Sinatra::NotFound" do it "cascades for subclasses of Sinatra::NotFound" do
mock_app { mock_app do
set :raise_errors, true set :raise_errors, true
error(FooNotFound) { "foo! not found." } error(FooNotFound) { "foo! not found." }
get '/' do get('/') { raise FooNotFound }
raise FooNotFound end
end
}
assert_nothing_raised { get '/' } assert_nothing_raised { get '/' }
assert_equal 404, status assert_equal 404, status
assert_equal 'foo! not found.', body assert_equal 'foo! not found.', body
end end
it 'has a not_found method for backwards compatibility' do it 'has a not_found method for backwards compatibility' do
mock_app { mock_app { not_found { "Lost, are we?" } }
not_found do
"Lost, are we?"
end
}
get '/test' get '/test'
assert_equal 404, status assert_equal 404, status
@ -166,12 +148,10 @@ class MappedErrorTest < Test::Unit::TestCase
base = Class.new(Sinatra::Base) base = Class.new(Sinatra::Base)
base.error(FooError) { 'base class' } base.error(FooError) { 'base class' }
mock_app(base) { mock_app(base) do
set :raise_errors, false set :raise_errors, false
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 'base class', body assert_equal 'base class', body
@ -181,13 +161,11 @@ class MappedErrorTest < Test::Unit::TestCase
base = Class.new(Sinatra::Base) base = Class.new(Sinatra::Base)
base.error(FooError) { 'base class' } base.error(FooError) { 'base class' }
mock_app(base) { mock_app(base) do
set :raise_errors, false set :raise_errors, false
error(FooError) { 'subclass' } error(FooError) { 'subclass' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 'subclass', body assert_equal 'subclass', body
@ -234,36 +212,36 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it "allows a stack of exception_handlers" do it "allows a stack of exception_handlers" do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(FirstError) { 'First!' } error(FirstError) { 'First!' }
error(SecondError) { 'Second!' } error(SecondError) { 'Second!' }
get('/'){ raise SecondError } get('/'){ raise SecondError }
} end
get '/' get '/'
assert_equal 500, status assert_equal 500, status
assert_equal 'Second!', body assert_equal 'Second!', body
end end
it "allows an exception handler to pass control to the next exception handler" do it "allows an exception handler to pass control to the next exception handler" do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(500, FirstError) { 'First!' } error(500, FirstError) { 'First!' }
error(500, SecondError) { pass } error(500, SecondError) { pass }
get('/') { raise 500 } get('/') { raise 500 }
} end
get '/' get '/'
assert_equal 500, status assert_equal 500, status
assert_equal 'First!', body assert_equal 'First!', body
end end
it "allows an exception handler to handle the exception" do it "allows an exception handler to handle the exception" do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(500, FirstError) { 'First!' } error(500, FirstError) { 'First!' }
error(500, SecondError) { 'Second!' } error(500, SecondError) { 'Second!' }
get('/') { raise 500 } get('/') { raise 500 }
} end
get '/' get '/'
assert_equal 500, status assert_equal 500, status
assert_equal 'Second!', body assert_equal 'Second!', body
@ -272,39 +250,33 @@ class MappedErrorTest < Test::Unit::TestCase
describe 'Custom Error Pages' do describe 'Custom Error Pages' do
it 'allows numeric status code mappings to be registered with ::error' do it 'allows numeric status code mappings to be registered with ::error' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(500) { 'Foo!' } error(500) { 'Foo!' }
get '/' do get('/') { [500, {}, 'Internal Foo Error'] }
[500, {}, 'Internal Foo Error'] end
end
}
get '/' get '/'
assert_equal 500, status assert_equal 500, status
assert_equal 'Foo!', body assert_equal 'Foo!', body
end end
it 'allows ranges of status code mappings to be registered with :error' do it 'allows ranges of status code mappings to be registered with :error' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(500..550) { "Error: #{response.status}" } error(500..550) { "Error: #{response.status}" }
get '/' do get('/') { [507, {}, 'A very special error'] }
[507, {}, 'A very special error'] end
end
}
get '/' get '/'
assert_equal 507, status assert_equal 507, status
assert_equal 'Error: 507', body assert_equal 'Error: 507', body
end end
it 'allows passing more than one range' do it 'allows passing more than one range' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error(409..411, 503..509) { "Error: #{response.status}" } error(409..411, 503..509) { "Error: #{response.status}" }
get '/' do get('/') { [507, {}, 'A very special error'] }
[507, {}, 'A very special error'] end
end
}
get '/' get '/'
assert_equal 507, status assert_equal 507, status
assert_equal 'Error: 507', body assert_equal 'Error: 507', body
@ -314,7 +286,7 @@ class MappedErrorTest < Test::Unit::TestCase
end end
it 'runs after exception mappings and overwrites body' do it 'runs after exception mappings and overwrites body' do
mock_app { mock_app do
set :raise_errors, false set :raise_errors, false
error FooError do error FooError do
response.status = 502 response.status = 502
@ -323,10 +295,8 @@ class MappedErrorTest < Test::Unit::TestCase
error(500) { 'from 500 handler' } error(500) { 'from 500 handler' }
error(502) { 'from custom error page' } error(502) { 'from custom error page' }
get '/' do get('/') { raise FooError }
raise FooError end
end
}
get '/' get '/'
assert_equal 502, status assert_equal 502, status
assert_equal 'from custom error page', body assert_equal 'from custom error page', body

View File

@ -7,7 +7,7 @@ class MarkabyTest < Test::Unit::TestCase
def markaby_app(&block) def markaby_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -67,9 +67,9 @@ class MarkabyTest < Test::Unit::TestCase
end end
it "allows passing locals" do it "allows passing locals" do
markaby_app do markaby_app {
markaby 'text value', :locals => { :value => 'foo' } markaby 'text value', :locals => { :value => 'foo' }
end }
assert ok? assert ok?
assert_equal 'foo', body assert_equal 'foo', body
end end

View File

@ -4,7 +4,7 @@ MarkdownTest = proc do
def markdown_app(&block) def markdown_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -48,7 +48,9 @@ MarkdownTest = proc do
end end
it "renders with file layouts" do it "renders with file layouts" do
markdown_app { markdown 'Hello World', :layout => :layout2, :layout_engine => :erb } markdown_app {
markdown 'Hello World', :layout => :layout2, :layout_engine => :erb
}
assert ok? assert ok?
assert_body "ERB Layout!\n<p>Hello World</p>" assert_body "ERB Layout!\n<p>Hello World</p>"
end end
@ -57,9 +59,7 @@ MarkdownTest = proc do
mock_app do mock_app do
template(:inner) { "hi" } template(:inner) { "hi" }
template(:outer) { "<outer><%= markdown :inner %></outer>" } template(:outer) { "<outer><%= markdown :inner %></outer>" }
get '/' do get('/') { erb :outer }
erb :outer
end
end end
get '/' get '/'

View File

@ -2,14 +2,14 @@ require File.expand_path('../helper', __FILE__)
class MiddlewareTest < Test::Unit::TestCase class MiddlewareTest < Test::Unit::TestCase
setup do setup do
@app = mock_app(Sinatra::Application) { @app = mock_app(Sinatra::Application) do
get '/*' do get('/*')do
response.headers['X-Tests'] = env['test.ran']. response.headers['X-Tests'] = env['test.ran'].
map { |n| n.split('::').last }. map { |n| n.split('::').last }.
join(', ') join(', ')
env['PATH_INFO'] env['PATH_INFO']
end end
} end
end end
class MockMiddleware < Struct.new(:app) class MockMiddleware < Struct.new(:app)

View File

@ -7,7 +7,7 @@ class NokogiriTest < Test::Unit::TestCase
def nokogiri_app(&block) def nokogiri_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -21,9 +21,7 @@ class NokogiriTest < Test::Unit::TestCase
it 'renders inline blocks' do it 'renders inline blocks' do
nokogiri_app do nokogiri_app do
@name = "Frank & Mary" @name = "Frank & Mary"
nokogiri do |xml| nokogiri { |xml| xml.couple @name }
xml.couple @name
end
end end
assert ok? assert ok?
assert_body %(<?xml version="1.0"?>\n<couple>Frank &amp; Mary</couple>\n) assert_body %(<?xml version="1.0"?>\n<couple>Frank &amp; Mary</couple>\n)
@ -51,9 +49,9 @@ class NokogiriTest < Test::Unit::TestCase
it "renders with file layouts" do it "renders with file layouts" do
next if Tilt::VERSION <= "1.1" next if Tilt::VERSION <= "1.1"
nokogiri_app do nokogiri_app {
nokogiri %(xml.em 'Hello World'), :layout => :layout2 nokogiri %(xml.em 'Hello World'), :layout => :layout2
end }
assert ok? assert ok?
assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n) assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n)
end end

View File

@ -7,7 +7,7 @@ class RadiusTest < Test::Unit::TestCase
def radius_app(&block) def radius_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -46,9 +46,9 @@ class RadiusTest < Test::Unit::TestCase
end end
it "allows passing locals" do it "allows passing locals" do
radius_app do radius_app {
radius '<r:value />', :locals => { :value => 'foo' } radius '<r:value />', :locals => { :value => 'foo' }
end }
assert ok? assert ok?
assert_equal 'foo', body assert_equal 'foo', body
end end

View File

@ -8,7 +8,7 @@ class RdocTest < Test::Unit::TestCase
def rdoc_app(&block) def rdoc_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
@ -41,7 +41,9 @@ class RdocTest < Test::Unit::TestCase
end end
it "renders with file layouts" do it "renders with file layouts" do
rdoc_app { rdoc 'Hello World', :layout => :layout2, :layout_engine => :erb } rdoc_app {
rdoc 'Hello World', :layout => :layout2, :layout_engine => :erb
}
assert ok? assert ok?
assert_body "ERB Layout!\n<p>Hello World</p>" assert_body "ERB Layout!\n<p>Hello World</p>"
end end
@ -50,9 +52,7 @@ class RdocTest < Test::Unit::TestCase
mock_app do mock_app do
template(:inner) { "hi" } template(:inner) { "hi" }
template(:outer) { "<outer><%= rdoc :inner %></outer>" } template(:outer) { "<outer><%= rdoc :inner %></outer>" }
get '/' do get('/') { erb :outer }
erb :outer
end
end end
get '/' get '/'

View File

@ -11,29 +11,17 @@ class ReadmeTest < Test::Unit::TestCase
section "Routes" do section "Routes" do
example do example do
mock_app do mock_app do
get '/' do get('/') { ".. show something .." }
".. show something .."
end
post '/' do post('/') { ".. create something .." }
".. create something .."
end
put '/' do put('/') { ".. replace something .." }
".. replace something .."
end
patch '/' do patch('/') { ".. modify something .." }
".. modify something .."
end
delete '/' do delete('/') { ".. annihilate something .." }
".. annihilate something .."
end
options '/' do options('/') { ".. appease something .." }
".. appease something .."
end
end end
get '/' get '/'
@ -57,7 +45,7 @@ class ReadmeTest < Test::Unit::TestCase
example do example do
mock_app do mock_app do
get '/hello/:name' do get('/hello/:name') do
# matches "GET /hello/foo" and "GET /hello/bar" # matches "GET /hello/foo" and "GET /hello/bar"
# params[:name] is 'foo' or 'bar' # params[:name] is 'foo' or 'bar'
"Hello #{params[:name]}!" "Hello #{params[:name]}!"
@ -72,11 +60,7 @@ class ReadmeTest < Test::Unit::TestCase
end end
example do example do
mock_app do mock_app { get('/hello/:name') { |n| "Hello #{n}!" } }
get '/hello/:name' do |n|
"Hello #{n}!"
end
end
get '/hello/foo' get '/hello/foo'
assert_body 'Hello foo!' assert_body 'Hello foo!'
@ -87,12 +71,12 @@ class ReadmeTest < Test::Unit::TestCase
example do example do
mock_app do mock_app do
get '/say/*/to/*' do get('/say/*/to/*') do
# matches /say/hello/to/world # matches /say/hello/to/world
params[:splat].inspect # => ["hello", "world"] params[:splat].inspect # => ["hello", "world"]
end end
get '/download/*.*' do get('/download/*.*') do
# matches /download/path/to/file.xml # matches /download/path/to/file.xml
params[:splat].inspect # => ["path/to/file", "xml"] params[:splat].inspect # => ["path/to/file", "xml"]
end end
@ -107,9 +91,9 @@ class ReadmeTest < Test::Unit::TestCase
example do example do
mock_app do mock_app do
get %r{/hello/([\w]+)} do get(%r{/hello/([\w]+)}) {
"Hello, #{params[:captures].first}!" "Hello, #{params[:captures].first}!"
end }
end end
get '/hello/foo' get '/hello/foo'
@ -121,9 +105,9 @@ class ReadmeTest < Test::Unit::TestCase
example do example do
mock_app do mock_app do
get %r{/hello/([\w]+)} do |c| get( %r{/hello/([\w]+)}) { |c|
"Hello, #{c}!" "Hello, #{c}!"
end }
end end
get '/hello/foo' get '/hello/foo'

View File

@ -3,9 +3,7 @@
require File.expand_path('../helper', __FILE__) require File.expand_path('../helper', __FILE__)
class ResponseTest < Test::Unit::TestCase class ResponseTest < Test::Unit::TestCase
setup do setup { @response = Sinatra::Response.new }
@response = Sinatra::Response.new
end
it "initializes with 200, text/html, and empty body" do it "initializes with 200, text/html, and empty body" do
assert_equal 200, @response.status assert_equal 200, @response.status

View File

@ -2,11 +2,7 @@ require File.expand_path('../helper', __FILE__)
class ResultTest < Test::Unit::TestCase class ResultTest < Test::Unit::TestCase
it "sets response.body when result is a String" do it "sets response.body when result is a String" do
mock_app { mock_app { get('/') { 'Hello World' } }
get '/' do
'Hello World'
end
}
get '/' get '/'
assert ok? assert ok?
@ -14,11 +10,7 @@ class ResultTest < Test::Unit::TestCase
end end
it "sets response.body when result is an Array of Strings" do it "sets response.body when result is an Array of Strings" do
mock_app { mock_app { get('/') { ['Hello', 'World'] } }
get '/' do
['Hello', 'World']
end
}
get '/' get '/'
assert ok? assert ok?
@ -26,13 +18,13 @@ class ResultTest < Test::Unit::TestCase
end end
it "sets response.body when result responds to #each" do it "sets response.body when result responds to #each" do
mock_app { mock_app do
get '/' do get('/') do
res = lambda { 'Hello World' } res = lambda { 'Hello World' }
def res.each ; yield call ; end def res.each ; yield call ; end
res return res
end end
} end
get '/' get '/'
assert ok? assert ok?
@ -40,11 +32,7 @@ class ResultTest < Test::Unit::TestCase
end end
it "sets response.body to [] when result is nil" do it "sets response.body to [] when result is nil" do
mock_app { mock_app { get( '/') { nil } }
get '/' do
nil
end
}
get '/' get '/'
assert ok? assert ok?
@ -53,9 +41,7 @@ class ResultTest < Test::Unit::TestCase
it "sets status, headers, and body when result is a Rack response tuple" do it "sets status, headers, and body when result is a Rack response tuple" do
mock_app { mock_app {
get '/' do get('/') { [203, {'Content-Type' => 'foo/bar'}, 'Hello World'] }
[203, {'Content-Type' => 'foo/bar'}, 'Hello World']
end
} }
get '/' get '/'
@ -65,11 +51,7 @@ class ResultTest < Test::Unit::TestCase
end end
it "sets status and body when result is a two-tuple" do it "sets status and body when result is a two-tuple" do
mock_app { mock_app { get('/') { [409, 'formula of'] } }
get '/' do
[409, 'formula of']
end
}
get '/' get '/'
assert_equal 409, status assert_equal 409, status
@ -78,18 +60,14 @@ class ResultTest < Test::Unit::TestCase
it "raises a ArgumentError when result is a non two or three tuple Array" do it "raises a ArgumentError when result is a non two or three tuple Array" do
mock_app { mock_app {
get '/' do get('/') { [409, 'formula of', 'something else', 'even more'] }
[409, 'formula of', 'something else', 'even more']
end
} }
assert_raise(ArgumentError) { get '/' } assert_raise(ArgumentError) { get '/' }
end end
it "sets status when result is a Fixnum status code" do it "sets status when result is a Fixnum status code" do
mock_app { mock_app { get('/') { 205 } }
get('/') { 205 }
}
get '/' get '/'
assert_equal 205, status assert_equal 205, status

View File

@ -11,16 +11,16 @@ module RouteAddedTest
end end
class RouteAddedHookTest < Test::Unit::TestCase class RouteAddedHookTest < Test::Unit::TestCase
setup { setup do
RouteAddedTest.routes.clear RouteAddedTest.routes.clear
RouteAddedTest.procs.clear RouteAddedTest.procs.clear
} end
it "should be notified of an added route" do it "should be notified of an added route" do
mock_app(Class.new(Sinatra::Base)) { mock_app(Class.new(Sinatra::Base)) do
register RouteAddedTest register RouteAddedTest
get('/') {} get('/') {}
} end
assert_equal [["GET", "/"], ["HEAD", "/"]], assert_equal [["GET", "/"], ["HEAD", "/"]],
RouteAddedTest.routes RouteAddedTest.routes
@ -38,21 +38,21 @@ class RouteAddedHookTest < Test::Unit::TestCase
end end
it "should only run once per extension" do it "should only run once per extension" do
mock_app(Class.new(Sinatra::Base)) { mock_app(Class.new(Sinatra::Base)) do
register RouteAddedTest register RouteAddedTest
register RouteAddedTest register RouteAddedTest
get('/') {} get('/') {}
} end
assert_equal [["GET", "/"], ["HEAD", "/"]], assert_equal [["GET", "/"], ["HEAD", "/"]],
RouteAddedTest.routes RouteAddedTest.routes
end end
it "should pass route blocks as an argument" do it "should pass route blocks as an argument" do
mock_app(Class.new(Sinatra::Base)) { mock_app(Class.new(Sinatra::Base)) do
register RouteAddedTest register RouteAddedTest
get('/') {} get('/') {}
} end
assert_kind_of Proc, RouteAddedTest.procs.first assert_kind_of Proc, RouteAddedTest.procs.first
end end

View File

@ -6,11 +6,11 @@ require 'sass'
class SassTest < Test::Unit::TestCase class SassTest < Test::Unit::TestCase
def sass_app(options = {}, &block) def sass_app(options = {}, &block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set options set options
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -36,9 +36,9 @@ class SassTest < Test::Unit::TestCase
end end
it 'defaults allows setting content type globally' do it 'defaults allows setting content type globally' do
sass_app(:sass => { :content_type => 'html' }) do sass_app(:sass => { :content_type => 'html' }) {
sass "#sass\n :background-color white\n" sass "#sass\n :background-color white\n"
end }
assert ok? assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type'] assert_equal "text/html;charset=utf-8", response['Content-Type']
end end
@ -56,50 +56,50 @@ class SassTest < Test::Unit::TestCase
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app { get('/') { sass :no_such_template } }
get('/') { sass :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
it "passes SASS options to the Sass engine" do it "passes SASS options to the Sass engine" do
sass_app { sass_app do
sass "#sass\n :background-color white\n :color black\n", sass(
"#sass\n :background-color white\n :color black\n",
:style => :compact :style => :compact
} )
end
assert ok? assert ok?
assert_equal "#sass { background-color: white; color: black; }\n", body assert_equal("#sass { background-color: white; color: black; }\n", body)
end end
it "passes default SASS options to the Sass engine" do it "passes default SASS options to the Sass engine" do
mock_app { mock_app do
set :sass, {:style => :compact} # default Sass style is :nested set :sass, {:style => :compact} # default Sass style is :nested
get '/' do get('/') { sass("#sass\n :background-color white\n :color black\n") }
sass "#sass\n :background-color white\n :color black\n" end
end
}
get '/' get '/'
assert ok? assert ok?
assert_equal "#sass { background-color: white; color: black; }\n", body assert_equal "#sass { background-color: white; color: black; }\n", body
end end
it "merges the default SASS options with the overrides" do it "merges the default SASS options with the overrides" do
mock_app { mock_app do
# default Sass attribute_syntax is :normal (with : in front) # default Sass attribute_syntax is :normal (with : in front)
set :sass, {:style => :compact, :attribute_syntax => :alternate } set :sass, {:style => :compact, :attribute_syntax => :alternate }
get '/' do get('/') { sass("#sass\n background-color: white\n color: black\n") }
sass "#sass\n background-color: white\n color: black\n" get('/raised') do
end
get '/raised' do
# retains global attribute_syntax settings # retains global attribute_syntax settings
sass "#sass\n :background-color white\n :color black\n", sass(
"#sass\n :background-color white\n :color black\n",
:style => :expanded :style => :expanded
)
end end
get '/expanded_normal' do get('/expanded_normal') do
sass "#sass\n :background-color white\n :color black\n", sass(
"#sass\n :background-color white\n :color black\n",
:style => :expanded, :attribute_syntax => :normal :style => :expanded, :attribute_syntax => :normal
)
end end
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "#sass { background-color: white; color: black; }\n", body assert_equal "#sass { background-color: white; color: black; }\n", body

View File

@ -6,11 +6,11 @@ require 'sass'
class ScssTest < Test::Unit::TestCase class ScssTest < Test::Unit::TestCase
def scss_app(options = {}, &block) def scss_app(options = {}, &block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set options set options
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -36,9 +36,9 @@ class ScssTest < Test::Unit::TestCase
end end
it 'defaults allows setting content type globally' do it 'defaults allows setting content type globally' do
scss_app(:scss => { :content_type => 'html' }) do scss_app(:scss => { :content_type => 'html' }) {
scss "#scss {\n background-color: white; }\n" scss "#scss {\n background-color: white; }\n"
end }
assert ok? assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type'] assert_equal "text/html;charset=utf-8", response['Content-Type']
end end
@ -56,28 +56,28 @@ class ScssTest < Test::Unit::TestCase
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app { get('/') { scss(:no_such_template) } }
get('/') { scss :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
it "passes scss options to the scss engine" do it "passes scss options to the scss engine" do
scss_app { scss_app do
scss "#scss {\n background-color: white;\n color: black\n}", scss(
"#scss {\n background-color: white;\n color: black\n}",
:style => :compact :style => :compact
} )
end
assert ok? assert ok?
assert_equal "#scss { background-color: white; color: black; }\n", body assert_equal "#scss { background-color: white; color: black; }\n", body
end end
it "passes default scss options to the scss engine" do it "passes default scss options to the scss engine" do
mock_app { mock_app do
set :scss, {:style => :compact} # default scss style is :nested set :scss, {:style => :compact} # default scss style is :nested
get '/' do get('/') {
scss "#scss {\n background-color: white;\n color: black;\n}" scss("#scss {\n background-color: white;\n color: black;\n}")
end }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "#scss { background-color: white; color: black; }\n", body assert_equal "#scss { background-color: white; color: black; }\n", body

View File

@ -21,11 +21,11 @@ end
class ServerTest < Test::Unit::TestCase class ServerTest < Test::Unit::TestCase
setup do setup do
mock_app { mock_app do
set :server, 'mock' set :server, 'mock'
set :bind, 'foo.local' set :bind, 'foo.local'
set :port, 9001 set :port, 9001
} end
$stderr = StringIO.new $stderr = StringIO.new
end end

View File

@ -2,12 +2,7 @@ require File.expand_path('../helper', __FILE__)
class SinatraTest < Test::Unit::TestCase class SinatraTest < Test::Unit::TestCase
it 'creates a new Sinatra::Base subclass on new' do it 'creates a new Sinatra::Base subclass on new' do
app = app = Sinatra.new { get('/') { 'Hello World' } }
Sinatra.new do
get '/' do
'Hello World'
end
end
assert_same Sinatra::Base, app.superclass assert_same Sinatra::Base, app.superclass
end end

View File

@ -5,10 +5,10 @@ require 'slim'
class SlimTest < Test::Unit::TestCase class SlimTest < Test::Unit::TestCase
def slim_app(&block) def slim_app(&block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
@ -25,34 +25,30 @@ class SlimTest < Test::Unit::TestCase
end end
it "renders with inline layouts" do it "renders with inline layouts" do
mock_app { mock_app do
layout { %(h1\n | THIS. IS. \n == yield.upcase ) } layout { %(h1\n | THIS. IS. \n == yield.upcase ) }
get('/') { slim 'em Sparta' } get('/') { slim 'em Sparta' }
} end
get '/' get '/'
assert ok? assert ok?
assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body
end end
it "renders with file layouts" do it "renders with file layouts" do
slim_app { slim_app { slim('| Hello World', :layout => :layout2) }
slim '| Hello World', :layout => :layout2
}
assert ok? assert ok?
assert_equal "<h1>Slim Layout!</h1><p>Hello World</p>", body assert_equal "<h1>Slim Layout!</h1><p>Hello World</p>", body
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { mock_app { get('/') { slim(:no_such_template) } }
get('/') { slim :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
HTML4_DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" HTML4_DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
it "passes slim options to the slim engine" do it "passes slim options to the slim engine" do
mock_app { get('/') { slim "x foo='bar'", :attr_wrapper => "'" }} mock_app { get('/') { slim("x foo='bar'", :attr_wrapper => "'") }}
get '/' get '/'
assert ok? assert ok?
assert_body "<x foo='bar'></x>" assert_body "<x foo='bar'></x>"
@ -61,7 +57,7 @@ class SlimTest < Test::Unit::TestCase
it "passes default slim options to the slim engine" do it "passes default slim options to the slim engine" do
mock_app do mock_app do
set :slim, :attr_wrapper => "'" set :slim, :attr_wrapper => "'"
get('/') { slim "x foo='bar'" } get('/') { slim("x foo='bar'") }
end end
get '/' get '/'
assert ok? assert ok?
@ -71,8 +67,8 @@ class SlimTest < Test::Unit::TestCase
it "merges the default slim options with the overrides and passes them to the slim engine" do it "merges the default slim options with the overrides and passes them to the slim engine" do
mock_app do mock_app do
set :slim, :attr_wrapper => "'" set :slim, :attr_wrapper => "'"
get('/') { slim "x foo='bar'" } get('/') { slim("x foo='bar'") }
get('/other') { slim "x foo='bar'", :attr_wrapper => '"' } get('/other') { slim("x foo='bar'", :attr_wrapper => '"') }
end end
get '/' get '/'
assert ok? assert ok?

View File

@ -2,10 +2,10 @@ require File.expand_path('../helper', __FILE__)
class StaticTest < Test::Unit::TestCase class StaticTest < Test::Unit::TestCase
setup do setup do
mock_app { mock_app do
set :static, true set :static, true
set :public_folder, File.dirname(__FILE__) set :public_folder, File.dirname(__FILE__)
} end
end end
it 'serves GET requests for files in the public directory' do it 'serves GET requests for files in the public directory' do
@ -82,10 +82,10 @@ class StaticTest < Test::Unit::TestCase
end end
it '404s when .. path traverses outside of public directory' do it '404s when .. path traverses outside of public directory' do
mock_app { mock_app do
set :static, true set :static, true
set :public_folder, File.dirname(__FILE__) + '/data' set :public_folder, File.dirname(__FILE__) + '/data'
} end
get "/../#{File.basename(__FILE__)}" get "/../#{File.basename(__FILE__)}"
assert not_found? assert not_found?
end end
@ -97,11 +97,30 @@ class StaticTest < Test::Unit::TestCase
should_be = file[range] should_be = file[range]
expected_range = "bytes #{range.begin}-#{range.end}/#{file.length}" expected_range = "bytes #{range.begin}-#{range.end}/#{file.length}"
assert_equal 206,response.status, "Should be HTTP/1.1 206 Partial content" assert_equal(
assert_equal should_be.length, response.body.length, "Unexpected response length for #{http_range}" 206,response.status,
assert_equal should_be, response.body, "Unexpected response data for #{http_range}" "Should be HTTP/1.1 206 Partial content"
assert_equal should_be.length.to_s, response['Content-Length'], "Incorrect Content-Length for #{http_range}" )
assert_equal expected_range, response['Content-Range'], "Incorrect Content-Range for #{http_range}" assert_equal(
should_be.length,
response.body.length,
"Unexpected response length for #{http_range}"
)
assert_equal(
should_be,
response.body,
"Unexpected response data for #{http_range}"
)
assert_equal(
should_be.length.to_s,
response['Content-Length'],
"Incorrect Content-Length for #{http_range}"
)
assert_equal(
expected_range,
response['Content-Range'],
"Incorrect Content-Range for #{http_range}"
)
end end
it 'handles valid byte ranges correctly' do it 'handles valid byte ranges correctly' do
@ -137,8 +156,16 @@ class StaticTest < Test::Unit::TestCase
request = Rack::MockRequest.new(@app) request = Rack::MockRequest.new(@app)
response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range)
assert_equal 200,response.status, "Invalid range '#{http_range}' should be ignored" assert_equal(
assert_equal nil,response['Content-Range'], "Invalid range '#{http_range}' should be ignored" 200,
response.status,
"Invalid range '#{http_range}' should be ignored"
)
assert_equal(
nil,
response['Content-Range'],
"Invalid range '#{http_range}' should be ignored"
)
end end
end end
@ -149,8 +176,16 @@ class StaticTest < Test::Unit::TestCase
request = Rack::MockRequest.new(@app) request = Rack::MockRequest.new(@app)
response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range)
assert_equal 416,response.status, "Unsatisfiable range '#{http_range}' should return 416" assert_equal(
assert_equal "bytes */#{length}",response['Content-Range'], "416 response should include actual length" 416,
response.status,
"Unsatisfiable range '#{http_range}' should return 416"
)
assert_equal(
"bytes */#{length}",
response['Content-Range'],
"416 response should include actual length"
)
end end
end end
@ -167,11 +202,17 @@ class StaticTest < Test::Unit::TestCase
assert headers.has_key?('Cache-Control') assert headers.has_key?('Cache-Control')
assert_equal headers['Cache-Control'], 'public' assert_equal headers['Cache-Control'], 'public'
@app.set :static_cache_control, [:public, :must_revalidate, {:max_age => 300}] @app.set(
:static_cache_control,
[:public, :must_revalidate, {:max_age => 300}]
)
env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}")
status, headers, body = @app.call(env) status, headers, body = @app.call(env)
assert headers.has_key?('Cache-Control') assert headers.has_key?('Cache-Control')
assert_equal headers['Cache-Control'], 'public, must-revalidate, max-age=300' assert_equal(
headers['Cache-Control'],
'public, must-revalidate, max-age=300'
)
end end
end end

View File

@ -5,7 +5,7 @@ class StreamingTest < Test::Unit::TestCase
it 'returns the concatinated body' do it 'returns the concatinated body' do
mock_app do mock_app do
get '/' do get('/') do
stream do |out| stream do |out|
out << "Hello" << " " out << "Hello" << " "
out << "World!" out << "World!"
@ -115,7 +115,9 @@ class StreamingTest < Test::Unit::TestCase
it 'gives access to route specific params' do it 'gives access to route specific params' do
mock_app do mock_app do
get('/:name') { stream { |o| o << params[:name] }} get('/:name') do
stream { |o| o << params[:name] }
end
end end
get '/foo' get '/foo'
assert_body 'foo' assert_body 'foo'

View File

@ -17,12 +17,12 @@ end
class TemplatesTest < Test::Unit::TestCase class TemplatesTest < Test::Unit::TestCase
def render_app(base=Sinatra::Base, options = {}, &block) def render_app(base=Sinatra::Base, options = {}, &block)
base, options = Sinatra::Base, base if base.is_a? Hash base, options = Sinatra::Base, base if base.is_a? Hash
mock_app(base) { mock_app(base) do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
set options set options
get '/', &block get('/', &block)
template(:layout3) { "Layout 3!\n" } template(:layout3) { "Layout 3!\n" }
} end
get '/' get '/'
end end
@ -35,26 +35,26 @@ class TemplatesTest < Test::Unit::TestCase
end end
it 'renders String templates directly' do it 'renders String templates directly' do
render_app { render :test, 'Hello World' } render_app { render(:test, 'Hello World') }
assert ok? assert ok?
assert_equal 'Hello World', body assert_equal 'Hello World', body
end end
it 'renders Proc templates using the call result' do it 'renders Proc templates using the call result' do
render_app { render :test, Proc.new {'Hello World'} } render_app { render(:test, Proc.new {'Hello World'}) }
assert ok? assert ok?
assert_equal 'Hello World', body assert_equal 'Hello World', body
end end
it 'looks up Symbol templates in views directory' do it 'looks up Symbol templates in views directory' do
render_app { render :test, :hello } render_app { render(:test, :hello) }
assert ok? assert ok?
assert_equal "Hello World!\n", body assert_equal "Hello World!\n", body
end end
it 'uses the default layout template if not explicitly overridden' do it 'uses the default layout template if not explicitly overridden' do
with_default_layout do with_default_layout do
render_app { render :test, :hello } render_app { render(:test, :hello) }
assert ok? assert ok?
assert_equal "Layout!\nHello World!\n", body assert_equal "Layout!\nHello World!\n", body
end end
@ -62,34 +62,40 @@ class TemplatesTest < Test::Unit::TestCase
it 'uses the default layout template if not really overriden' do it 'uses the default layout template if not really overriden' do
with_default_layout do with_default_layout do
render_app { render :test, :hello, :layout => true } render_app { render(:test, :hello, :layout => true) }
assert ok? assert ok?
assert_equal "Layout!\nHello World!\n", body assert_equal "Layout!\nHello World!\n", body
end end
end end
it 'uses the layout template specified' do it 'uses the layout template specified' do
render_app { render :test, :hello, :layout => :layout2 } render_app { render(:test, :hello, :layout => :layout2) }
assert ok? assert ok?
assert_equal "Layout 2!\nHello World!\n", body assert_equal "Layout 2!\nHello World!\n", body
end end
it 'uses layout templates defined with the #template method' do it 'uses layout templates defined with the #template method' do
render_app { render :test, :hello, :layout => :layout3 } render_app { render(:test, :hello, :layout => :layout3) }
assert ok? assert ok?
assert_equal "Layout 3!\nHello World!\n", body assert_equal "Layout 3!\nHello World!\n", body
end end
it 'avoids wrapping layouts around nested templates' do it 'avoids wrapping layouts around nested templates' do
render_app { render :str, :nested, :layout => :layout2 } render_app { render(:str, :nested, :layout => :layout2) }
assert ok? assert ok?
assert_equal "<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>", body assert_equal(
"<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>",
body
)
end end
it 'allows explicitly wrapping layouts around nested templates' do it 'allows explicitly wrapping layouts around nested templates' do
render_app { render :str, :explicitly_nested, :layout => :layout2 } render_app { render(:str, :explicitly_nested, :layout => :layout2) }
assert ok? assert ok?
assert_equal "<h1>String Layout!</h1>\n<content><h1>String Layout!</h1>\n<h1>Hello From String</h1></content>", body assert_equal(
"<h1>String Layout!</h1>\n<content><h1>String Layout!</h1>\n<h1>Hello From String</h1></content>",
body
)
end end
it 'two independent render calls do not disable layouts' do it 'two independent render calls do not disable layouts' do
@ -98,7 +104,10 @@ class TemplatesTest < Test::Unit::TestCase
render :str, :nested, :layout => :layout2 render :str, :nested, :layout => :layout2
end end
assert ok? assert ok?
assert_equal "<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>", body assert_equal(
"<h1>String Layout!</h1>\n<content><h1>Hello From String</h1></content>",
body
)
end end
it 'is possible to use partials in layouts' do it 'is possible to use partials in layouts' do
@ -111,54 +120,50 @@ class TemplatesTest < Test::Unit::TestCase
end end
it 'loads templates from source file' do it 'loads templates from source file' do
mock_app { enable :inline_templates } mock_app { enable(:inline_templates) }
assert_equal "this is foo\n\n", @app.templates[:foo][0] assert_equal "this is foo\n\n", @app.templates[:foo][0]
assert_equal "X\n= yield\nX\n", @app.templates[:layout][0] assert_equal "X\n= yield\nX\n", @app.templates[:layout][0]
end end
it 'ignores spaces after names of inline templates' do it 'ignores spaces after names of inline templates' do
mock_app { enable :inline_templates } mock_app { enable(:inline_templates) }
assert_equal "There's a space after 'bar'!\n\n", @app.templates[:bar][0] assert_equal "There's a space after 'bar'!\n\n", @app.templates[:bar][0]
assert_equal "this is not foo\n\n", @app.templates[:"foo bar"][0] assert_equal "this is not foo\n\n", @app.templates[:"foo bar"][0]
end end
it 'loads templates from given source file' do it 'loads templates from given source file' do
mock_app { set :inline_templates, __FILE__ } mock_app { set(:inline_templates, __FILE__) }
assert_equal "this is foo\n\n", @app.templates[:foo][0] assert_equal "this is foo\n\n", @app.templates[:foo][0]
end end
test 'inline_templates ignores IO errors' do test 'inline_templates ignores IO errors' do
assert_nothing_raised { assert_nothing_raised { mock_app { set(:inline_templates, '/foo/bar') } }
mock_app {
set :inline_templates, '/foo/bar'
}
}
assert @app.templates.empty? assert @app.templates.empty?
end end
it 'allows unicode in inline templates' do it 'allows unicode in inline templates' do
mock_app { set :inline_templates, __FILE__ } mock_app { set(:inline_templates, __FILE__) }
assert_equal "Den som tror at hemma det är där man bor har aldrig vart hos mig.\n\n", assert_equal(
"Den som tror at hemma det är där man bor har aldrig vart hos mig.\n\n",
@app.templates[:umlaut][0] @app.templates[:umlaut][0]
)
end end
it 'loads templates from specified views directory' do it 'loads templates from specified views directory' do
render_app { render :test, :hello, :views => settings.views + '/foo' } render_app { render( :test, :hello, :views => settings.views + '/foo') }
assert_equal "from another views directory\n", body assert_equal "from another views directory\n", body
end end
it 'passes locals to the layout' do it 'passes locals to the layout' do
mock_app { mock_app do
template :my_layout do template(:my_layout) { 'Hello <%= name %>!<%= yield %>' }
'Hello <%= name %>!<%= yield %>'
end
get '/' do get('/') do
erb '<p>content</p>', { :layout => :my_layout }, { :name => 'Mike'} erb('<p>content</p>', { :layout => :my_layout }, { :name => 'Mike'})
end end
} end
get '/' get '/'
assert ok? assert ok?
@ -168,18 +173,22 @@ class TemplatesTest < Test::Unit::TestCase
it 'loads templates defined in subclasses' do it 'loads templates defined in subclasses' do
base = Class.new(Sinatra::Base) base = Class.new(Sinatra::Base)
base.template(:foo) { 'bar' } base.template(:foo) { 'bar' }
render_app(base) { render :test, :foo } render_app(base) { render(:test, :foo) }
assert ok? assert ok?
assert_equal 'bar', body assert_equal 'bar', body
end end
it 'allows setting default content type per template engine' do it 'allows setting default content type per template engine' do
render_app(:str => { :content_type => :txt }) { render :str, 'foo' } render_app(:str => { :content_type => :txt }) {
render :str, 'foo'
}
assert_equal 'text/plain;charset=utf-8', response['Content-Type'] assert_equal 'text/plain;charset=utf-8', response['Content-Type']
end end
it 'setting default content type does not affect other template engines' do it 'setting default content type does not affect other template engines' do
render_app(:str => { :content_type => :txt }) { render :test, 'foo' } render_app(:str => { :content_type => :txt }) {
render :test, 'foo'
}
assert_equal 'text/html;charset=utf-8', response['Content-Type'] assert_equal 'text/html;charset=utf-8', response['Content-Type']
end end
@ -196,11 +205,11 @@ class TemplatesTest < Test::Unit::TestCase
base.template(:foo) { 'template in superclass' } base.template(:foo) { 'template in superclass' }
assert_equal 'template in superclass', base.templates[:foo].first.call assert_equal 'template in superclass', base.templates[:foo].first.call
mock_app(base) { mock_app(base) do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
template(:foo) { 'template in subclass' } template(:foo) { 'template in subclass' }
get('/') { render :test, :foo } get('/') { render :test, :foo }
} end
assert_equal 'template in subclass', @app.templates[:foo].first.call assert_equal 'template in subclass', @app.templates[:foo].first.call
get '/' get '/'
@ -240,11 +249,9 @@ class TemplatesTest < Test::Unit::TestCase
it "passes scope to the template" do it "passes scope to the template" do
mock_app do mock_app do
template :scoped do template(:scoped) { 'Hello <%= foo %>' }
'Hello <%= foo %>'
end
get '/' do get('/') do
some_scope = Object.new some_scope = Object.new
def some_scope.foo() 'World!' end def some_scope.foo() 'World!' end
erb :scoped, :scope => some_scope erb :scoped, :scope => some_scope
@ -263,9 +270,7 @@ class TemplatesTest < Test::Unit::TestCase
Array(views).each { |v| super(v, name, engine, &block) } Array(views).each { |v| super(v, name, engine, &block) }
end end
get('/:name') do get('/:name') { render(:str, params[:name].to_sym) }
render :str, params[:name].to_sym
end
end end
get '/in_a' get '/in_a'

View File

@ -7,32 +7,32 @@ class TextileTest < Test::Unit::TestCase
def textile_app(&block) def textile_app(&block)
mock_app do mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
end end
get '/' get '/'
end end
it 'renders inline textile strings' do it 'renders inline textile strings' do
textile_app { textile 'h1. Hiya' } textile_app { textile('h1. Hiya') }
assert ok? assert ok?
assert_equal "<h1>Hiya</h1>", body assert_equal "<h1>Hiya</h1>", body
end end
it 'renders .textile files in views path' do it 'renders .textile files in views path' do
textile_app { textile :hello } textile_app { textile(:hello) }
assert ok? assert ok?
assert_equal "<h1>Hello From Textile</h1>", body assert_equal "<h1>Hello From Textile</h1>", body
end end
it "raises error if template not found" do it "raises error if template not found" do
mock_app { get('/') { textile :no_such_template } } mock_app { get('/') { textile(:no_such_template) } }
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
it "renders with inline layouts" do it "renders with inline layouts" do
mock_app do mock_app do
layout { 'THIS. IS. #{yield.upcase}!' } layout { 'THIS. IS. #{yield.upcase}!' }
get('/') { textile 'Sparta', :layout_engine => :str } get('/') { textile('Sparta', :layout_engine => :str) }
end end
get '/' get '/'
assert ok? assert ok?
@ -40,7 +40,9 @@ class TextileTest < Test::Unit::TestCase
end end
it "renders with file layouts" do it "renders with file layouts" do
textile_app { textile 'Hello World', :layout => :layout2, :layout_engine => :erb } textile_app {
textile('Hello World', :layout => :layout2, :layout_engine => :erb)
}
assert ok? assert ok?
assert_body "ERB Layout!\n<p>Hello World</p>" assert_body "ERB Layout!\n<p>Hello World</p>"
end end
@ -49,9 +51,7 @@ class TextileTest < Test::Unit::TestCase
mock_app do mock_app do
template(:inner) { "hi" } template(:inner) { "hi" }
template(:outer) { "<outer><%= textile :inner %></outer>" } template(:outer) { "<outer><%= textile :inner %></outer>" }
get '/' do get('/') { erb :outer }
erb :outer
end
end end
get '/' get '/'

View File

@ -5,71 +5,77 @@ require 'yajl'
class YajlTest < Test::Unit::TestCase class YajlTest < Test::Unit::TestCase
def yajl_app(&block) def yajl_app(&block)
mock_app { mock_app do
set :views, File.dirname(__FILE__) + '/views' set :views, File.dirname(__FILE__) + '/views'
get '/', &block get('/', &block)
} end
get '/' get '/'
end end
it 'renders inline Yajl strings' do it 'renders inline Yajl strings' do
yajl_app { yajl 'json = { :foo => "bar" }' } yajl_app { yajl('json = { :foo => "bar" }') }
assert ok? assert ok?
assert_body '{"foo":"bar"}' assert_body '{"foo":"bar"}'
end end
it 'renders .yajl files in views path' do it 'renders .yajl files in views path' do
yajl_app { yajl :hello } yajl_app { yajl(:hello) }
assert ok? assert ok?
assert_body '{"yajl":"hello"}' assert_body '{"yajl":"hello"}'
end end
it 'raises error if template not found' do it 'raises error if template not found' do
mock_app { mock_app { get('/') { yajl(:no_such_template) } }
get('/') { yajl :no_such_template }
}
assert_raise(Errno::ENOENT) { get('/') } assert_raise(Errno::ENOENT) { get('/') }
end end
it 'accepts a :locals option' do it 'accepts a :locals option' do
yajl_app { yajl_app do
locals = { :object => { :foo => 'bar' } } locals = { :object => { :foo => 'bar' } }
yajl 'json = object', :locals => locals yajl 'json = object', :locals => locals
} end
assert ok? assert ok?
assert_body '{"foo":"bar"}' assert_body '{"foo":"bar"}'
end end
it 'accepts a :scope option' do it 'accepts a :scope option' do
yajl_app { yajl_app do
scope = { :object => { :foo => 'bar' } } scope = { :object => { :foo => 'bar' } }
yajl 'json = self[:object]', :scope => scope yajl 'json = self[:object]', :scope => scope
} end
assert ok? assert ok?
assert_body '{"foo":"bar"}' assert_body '{"foo":"bar"}'
end end
it 'decorates the json with a callback' do it 'decorates the json with a callback' do
yajl_app { yajl_app do
yajl 'json = { :foo => "bar" }', { :callback => 'baz' } yajl(
} 'json = { :foo => "bar" }',
{ :callback => 'baz' }
)
end
assert ok? assert ok?
assert_body 'baz({"foo":"bar"});' assert_body 'baz({"foo":"bar"});'
end end
it 'decorates the json with a variable' do it 'decorates the json with a variable' do
yajl_app { yajl_app do
yajl 'json = { :foo => "bar" }', { :variable => 'qux' } yajl(
} 'json = { :foo => "bar" }',
{ :variable => 'qux' }
)
end
assert ok? assert ok?
assert_body 'var qux = {"foo":"bar"};' assert_body 'var qux = {"foo":"bar"};'
end end
it 'decorates the json with a callback and a variable' do it 'decorates the json with a callback and a variable' do
yajl_app { yajl_app do
yajl 'json = { :foo => "bar" }', yajl(
'json = { :foo => "bar" }',
{ :callback => 'baz', :variable => 'qux' } { :callback => 'baz', :variable => 'qux' }
} )
end
assert ok? assert ok?
assert_body 'var qux = {"foo":"bar"}; baz(qux);' assert_body 'var qux = {"foo":"bar"}; baz(qux);'
end end