Created
July 9, 2013 06:22
-
-
Save speedmax/5955108 to your computer and use it in GitHub Desktop.
How to test rack middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
# Based on https://github.com/rails/ssl_requirement/blob/master/lib/ssl_requirement.rb | |
class SslRequirement | |
def initialize(app, options= {}) | |
@app = app | |
@allowed = options[:allowed] | |
@required = options[:required] | |
end | |
def call(env) | |
@env = env | |
redirect_to = url_with_proper_protocol | |
if redirect_to.is_a?(String) | |
return [ 301, {"Location" => redirect_to}, [] ] | |
end | |
@app.call @env | |
end | |
def ssl_required? | |
@required && host_and_path =~ @required | |
end | |
def ssl_allowed? | |
@allowed && host_and_path =~ @allowed | |
end | |
private | |
def request | |
Rack::Request.new @env | |
end | |
def host_and_path | |
request.host + request.fullpath | |
end | |
def url_with_proper_protocol | |
return true if ssl_allowed? | |
return_to = nil | |
if ssl_required? && request.port != 443 | |
return_to = "https://" + host_and_path | |
elsif request.port == 443 && !ssl_required? | |
return_to = "http://" + host_and_path | |
end | |
return_to | |
end | |
end | |
describe SslRequirement do | |
let(:app) { ->(env) { [200, env, "app"] } } | |
let :middleware do | |
SslRequirement.new(app, required: /^admin.example.com/ ) | |
end | |
it "redirects to secure protocol" do | |
code, env = middleware.call env_for('http://admin.example.com') | |
code.should == 301 | |
env['Location'].should == 'https://admin.example.com/' | |
end | |
it "shouldn't redirect for non matching ssl requirement" do | |
code, env = middleware.call env_for('http://help.example.com') | |
code.should == 200 | |
end | |
it "redirects to non-secure site for non matching ssl requirement'" do | |
code, env = middleware.call env_for('https://content.example.com') | |
code.should == 301 | |
env["Location"].should == "http://content.example.com/" | |
end | |
it "allows certain url with secured protocol" do | |
middleware = SslRequirement.new(app, allowed: /^help.example.com/ ) | |
code, env = middleware.call env_for('https://help.example.com') | |
code.should == 200 | |
env["Location"].should == nil | |
end | |
def env_for url, opts={} | |
Rack::MockRequest.env_for(url, opts) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment