更具体地说,我在谈论的是 sentry-raven
和 sinatra
。我看到了测试 sinatra
应用程序或中间件的示例。但是我没有看到测试特定中间件是否存在的示例。或者我应该测试行为而不是配置(或我应该如何称呼它)?
在Sinatra源代码中,有一种使用env来检查中间件是否已经存在的方法:
# Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing,
# if another CommonLogger is already in the middleware chain.
class CommonLogger < Rack::CommonLogger
def call(env)
env['sinatra.commonlogger'] ? @app.call(env) : super
end
。
get "/env-keys" do
env.keys.inspect
end
只有在中间件向env哈希表插入了某些内容时,它才会显示给你中间件,例如:
class MyBad
def initialize app, options={}
@app = app
@options = options
end
def call env
@app.call env.merge("mybad" => "I'm sorry!")
end
end
输出:
["SERVER_SOFTWARE", "SERVER_NAME", "rack.input", "rack.version", "rack.errors", "rack.multithread", "rack.multiprocess", "rack.run_once", "REQUEST_METHOD", "REQUEST_PATH", "PATH_INFO", "REQUEST_URI", "HTTP_VERSION", "HTTP_HOST", "HTTP_CONNECTION", "HTTP_CACHE_CONTROL", "HTTP_ACCEPT", "HTTP_USER_AGENT", "HTTP_DNT", "HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE", "GATEWAY_INTERFACE", "SERVER_PORT", "QUERY_STRING", "SERVER_PROTOCOL", "rack.url_scheme", "SCRIPT_NAME", "REMOTE_ADDR", "async.callback", "async.close", "rack.logger", "mybad", "rack.request.query_string", "rack.request.query_hash", "sinatra.route"]
middleware
的方法: # Middleware used in this class and all superclasses.
def middleware
if superclass.respond_to?(:middleware)
superclass.middleware + @middleware
else
@middleware
end
end
require 'sinatra/base'
class AnExample < Sinatra::Base
use MyBad
warn "self.middleware = #{self.middleware}"
输出:
self.middleware = [[MyBad, [], nil]]
在ruby-raven
的小伙伴们的帮助下,我们得到了这个:
ENV['RACK_ENV'] = 'test'
# the app: start
require 'sinatra'
require 'sentry-raven'
Raven.configure(true) do |config|
config.dsn = '...'
end
use Raven::Rack
get '/' do
'Hello, world!'
end
# the app: end
require 'rspec'
require 'rack/test'
Raven.configure do |config|
logger = ::Logger.new(STDOUT)
logger.level = ::Logger::WARN
config.logger = logger
end
describe 'app' do
include Rack::Test::Methods
def app
@app || Sinatra::Application
end
class TestRavenError < StandardError; end
it 'sends errors to sentry' do
@app = Class.new Sinatra::Application do
get '/' do
raise TestRavenError
end
end
allow(Raven.client).to receive(:send).and_return(true)
begin
get '/'
rescue TestRavenError
end
expect(Raven.client).to have_received(:send)
end
end
或者如果发送请求的raven
成为了问题(当测试失败不是因为底层错误,而是因为raven
发送请求时),可以禁用它们:
Raven.configure(true) do |config|
config.should_send = Proc.new { false }
end
并且模拟 Raven.send_or_skip
:
...
allow(Raven).to receive(:send_or_skip).and_return(true)
begin
get '/'
rescue TestRavenError
end
expect(Raven).to have_received(:send_or_skip)
...
should_receive
进行模拟。 - ian