Added context specs

This commit is contained in:
Sdogruyol 2015-10-28 20:52:34 +02:00
parent ad6baba12b
commit 5376eb8bb2
5 changed files with 36 additions and 27 deletions

23
spec/context_spec.cr Normal file
View file

@ -0,0 +1,23 @@
require "./spec_helper"
describe "Context" do
it "has a default content type" do
kemal = Kemal::Handler.new
kemal.add_route "GET", "/" do |env|
"Hello"
end
request = HTTP::Request.new("GET", "/")
response = kemal.call(request)
response.headers["Content-Type"].should eq("text/plain")
end
it "sets content type" do
kemal = Kemal::Handler.new
kemal.add_route "GET", "/" do |env|
env.set_content_type "application/json"
end
request = HTTP::Request.new("GET", "/")
response = kemal.call(request)
response.headers["Content-Type"].should eq("application/json")
end
end

View file

@ -40,14 +40,4 @@ describe "Kemal::Handler" do
response = kemal.call(request)
response.body.should eq("hello world")
end
it "sets content type" do
kemal = Kemal::Handler.new
kemal.add_route "GET", "/" do |env|
env.response.content_type = "application/json"
end
request = HTTP::Request.new("GET", "/")
response = kemal.call(request)
response.headers["Content-Type"].should eq("application/json")
end
end

View file

@ -1,7 +1,6 @@
require "./spec_helper"
describe "ParamParser" do
it "parses query params" do
route = Route.new "POST", "/" do |env|
hasan = env.params["hasan"]
@ -23,5 +22,4 @@ describe "ParamParser" do
params = Kemal::ParamParser.new(route, request).parse
params.should eq({"hasan" => "cemal", "name" => "serdar", "age" => "99"})
end
end

View file

@ -1,15 +1,13 @@
class Kemal::Context
getter request
getter params
getter content_type
def initialize(@request, @params)
@content_type = "text/plain"
end
def response
@response ||= Response.new
end
def response?
@response
def set_content_type(content_type)
@content_type = content_type
end
end

View file

@ -26,7 +26,7 @@ class Kemal::Handler < HTTP::Handler
context = Context.new(request, params.not_nil!)
begin
body = route.handler.call(context).to_s
content_type = context.response?.try(&.content_type) || "text/plain"
content_type = context.content_type
return HTTP::Response.ok(content_type, body)
rescue ex
return HTTP::Response.error("text/plain", ex.to_s)