Skip to content

Instantly share code, notes, and snippets.

@tejasbubane
Last active November 13, 2019 09:10
Show Gist options
  • Save tejasbubane/c046640bfb1964e2678aaa138ca8e4bb to your computer and use it in GitHub Desktop.
Save tejasbubane/c046640bfb1964e2678aaa138ca8e4bb to your computer and use it in GitHub Desktop.
Unit testing rack middlewares
# Make sure rack & rspec are installed -> gem install rack rspec
# Run this script using rspec -> rspec middleware.rb
require 'rack'
class BlockActions
def initialize(app)
@app = app
end
def call(env)
unless env["HTTP_X_CLIENT"] == "mobile" && env["HTTP_X_MOBILE_USER_ID"]
return [
400, # status
{ "Content-Type" => "application/json" }, # headers
["Invalid Request"] # response body
]
end
@app.call(env)
end
end
require 'rspec'
describe BlockActions do
# Mock env to pass in middleware
let(:env) { Rack::MockRequest.env_for }
# dummy app to validate success
let(:app) { ->(env) { [200, {}, "success"] } }
subject { BlockActions.new(app) }
it "allows if client & user-id headers are present" do
env["HTTP_X_CLIENT"] = "mobile"
env["HTTP_X_MOBILE_USER_ID"] = 1
status, _headers, _response = subject.call(env)
expect(status).to eq(200)
end
it "does not allow if client is missing" do
env["HTTP_X_MOBILE_USER_ID"] = 1
status, _headers, _response = subject.call(env)
expect(status).to eq(400)
end
it "does not allow if mobile-user-id is missing" do
env["HTTP_X_CLIENT"] = "mobile"
status, _headers, _response = subject.call(env)
expect(status).to eq(400)
end
it "does not allow if client is not mobile" do
env["HTTP_X_CLIENT"] = "jared"
status, _headers, _response = subject.call(env)
expect(status).to eq(400)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment