我已经写了一些Rack-Middleware,现在我正试着用Rspec测试它。但是所有的Rack-Middleware都是用一个' app‘参数实例化的,这个参数代表了Rails应用本身。你们是如何在Rspec中模拟这个的?
例如,
describe MyMiddleWare do
let(:app) { # How do I mock a Rails app object here? }
subject { MyMiddleWare.new(app: app) }
it 'should blah blah blah' do
# a bunch of tests go here
end
end发布于 2014-02-12 17:42:59
你只需要世界上最简单的Rack应用程序:
let(:app) { lambda {|env| [200, {'Content-Type' => 'text/plain'}, ['OK']]} }另外,你的中间件的构造函数应该接收一个app作为它的第一个参数,而不是一个散列,所以它应该是:
subject { MyMiddleWare.new(app) }不过,您的测试很可能需要确定中间件对请求的影响。因此,您可能会编写一个稍微复杂一些的rack应用程序来监视您的中间件。
class MockRackApp
attr_reader :request_body
def initialize
@request_headers = {}
end
def call(env)
@env = env
@request_body = env['rack.input'].read
[200, {'Content-Type' => 'text/plain'}, ['OK']]
end
def [](key)
@env[key]
end
end然后,您可能希望使用Rack::MockRequest来实际发送请求。类似于:
describe MyMiddleWare do
let(:app) { MockRackApp.new }
subject { described_class.new(app) }
context "when called with a POST request" do
let(:request) { Rack::MockRequest.new(subject) }
before(:each) do
request.post("/some/path", input: post_data, 'CONTENT_TYPE' => 'text/plain')
end
context "with some particular data" do
let(:post_data) { "String or IO post data" }
it "passes the request through unchanged" do
expect(app['CONTENT_TYPE']).to eq('text/plain')
expect(app['CONTENT_LENGTH'].to_i).to eq(post_data.length)
expect(app.request_body).to eq(post_data)
end
end
end
end发布于 2013-07-23 18:29:55
我认为您应该使用请求规范来模拟http请求(您的中间件应该包含在rails中间件堆栈中)。有关rspec请求规范here的更多详细信息,请参阅。
更新单元我想我已经通过::Unit找到了您需要的东西,但是RSpec:rack-ssl-enforcer的重写很容易
发布于 2013-12-04 07:51:17
我是这样测试我的
describe Support::CharConverter do
let(:env_hash) do
{
"HTTP_REFERER" => "",
"PATH_INFO" => "foo",
"QUERY_STRING" => "bar",
"REQUEST_PATH" => "is",
"REQUEST_URI" => "here",
}
end
subject do
Support::CharConverter.new(env_hash)
end
context 'sanitize_env' do
it 'should keep key values the same if nothing to sanitize' do
sanitized_hash = subject.sanitize_env(env_hash)
# k = env_hash.keys[5]
# v = env_hash.values[5]
env_hash.each do |k, v|
sanitized_hash[k].encoding.name.should eq("US-ASCII")
sanitized_hash[k].should eq(v)
sanitized_hash[k].valid_encoding?.should eq(true)
end
end
end
endhttps://stackoverflow.com/questions/17506567
复制相似问题