请考虑此测试:
def test_ok_on_second_request
bad_response = @request.get "/bad-response"
assert_equal 404, bad_response.status
good_response = @request.get "/test-title"
assert_equal 200, good_response.status
assert_equal "text/html", good_response.content_type
end
我确信/test-title
是一条有效的道路。应该返回200
的断言实际上是返回404
。 Rack如何为同一请求返回两个不同的结果?
这是项目中Server类的代码:
module Blogrite
class Server
attr_accessor :status, :mimetype, :body, :provider
def initialize *args, &block
@status, @mimetype = 200, "text/html"
provider = args[0][:with].nil? ? :filesystem : args[0][:with]
@provider = Blogrite.const_get(provider.capitalize).new
# p "Server is running with #{@provider.class}."
end
def call env
begin
article = go env['PATH_INFO'].delete("/")
rescue Blogrite::Article::NoBodyError
@status = 404
end
@status = 404 if !article
@status = 403 if env["REQUEST_METHOD"] == 'POST'
@mimetype = "text/css" if env["PATH_INFO"].include?("css")
@body = if article then article.render
elsif env.respond_to?(:to_yaml) then "<pre>#{env.to_yaml}</pre>"
else "oops"
end
[@status,{ "Content-Type" => @mimetype},[@body]]
end
def go path
f = @provider.fetch path
Article.parse f unless f.nil?
end
end
end
整个工作流程太大,我无法将其粘贴,但您可以在Github上查看项目。感谢您的帮助,谢谢。
答案 0 :(得分:1)
问题的解决方案就像在@status
函数中初始化call
一样简单。
class Server
attr_accessor :status, :mimetype, :body, :provider
def initialize *args, &block
- @status, @mimetype = 200, "text/html"
provider = args[0][:with].nil? ? :filesystem : args[0][:with]
@provider = Blogrite.const_get(provider.capitalize).new
# p "Server is running with #{@provider.class}."
end
def call env
begin
- article = go env['PATH_INFO'].delete("/")
+ @status, @mimetype = 200, "text/html"
+ article = go env['PATH_INFO'].delete("/")
rescue Blogrite::Article::NoBodyError
@status = 404
end
这样,机架实例 - 只被调用一次 - 不在请求的范围之内。每个调用函数都应该有自己的默认值,而不是服务器类。
感谢@rubenfonseca帮助我。