Sha256: 8e10e16c420c1e87935c84cc1c83448ea6bf9009e704303574723919a965a857

Contents?: true

Size: 1.42 KB

Versions: 2

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

<% if 'test-unit' == options[:test_framework] -%>
require_relative 'rack_test_assertions'
<% end -%>
<% if 'rspec' == options[:test_framework] -%>
require_relative 'rack_matchers'
<% end -%>

# Helpers for running Rack-based tests or specs. Decorates normal Rack methods
# with an optional `:as` parameter. If present, the `rack.session` will
# include the value of the given user's ID, effectively signing them in for
# the request.
#
# Example
# ```
# # Find or create a user. You can name the class anything you'd like, the
# # only requirement is that it responds to a `id` method.
# user = User.new(id: 1) # or User.find, etc.
# get '/', as: user
# ```
#
# The above will add a `current_user` to the `rack.session` with a value of
# the user's ID.
#
module RackHelpers
  include Rack::Test::Methods
<% if 'test-unit' == options[:test_framework] -%>
  include Rack::Test::Assertions
<% end -%>

  %w[get post put patch delete options].each do |type|
    define_method(type) do |uri, params={}, env={}, &block|
      extract_user!(params, env)
      super uri, params, env, &block
    end
  end

  private

  def extract_user!(params, env)
    user = params.delete(:as)
    return unless user

    if env.key?('rack.session')
      env['rack.session'].merge!(current_user: user.id)
    else
      env.merge!({ 'rack.session' => { current_user: user.id } })
    end
  end

  def app
    Sinatra::Application
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hoboken-0.10.0 lib/hoboken/templates/support/rack_helpers.rb.tt
hoboken-0.9.0 lib/hoboken/templates/support/rack_helpers.rb.tt