From 69d4835d88fafd2bf490d27f9f1535c615fff62f Mon Sep 17 00:00:00 2001 From: Per Lundberg Date: Wed, 12 Jul 2017 09:13:11 +0300 Subject: [PATCH] Rubocop fixes This makes the :cop: be happy. A lot of this is just: - rubocop -a (auto-fix) - rubocop --auto-gen (generate todo config) But, the good part about this is that we can now run Rubocop on each Travis build, to ensure that _new code_ follows the Rubocop rules as defined in .rubocop.yml --- .rubocop.yml | 8 +- .rubocop_todo.yml | 102 +++++ Rakefile | 19 +- Thorfile | 18 +- lib/rack/mock_session.rb | 15 +- lib/rack/test.rb | 120 +++--- lib/rack/test/cookie_jar.rb | 56 ++- lib/rack/test/methods.rb | 43 +- lib/rack/test/mock_digest_request.rb | 6 +- lib/rack/test/uploaded_file.rb | 12 +- lib/rack/test/utils.rb | 52 +-- rack-test.gemspec | 2 +- spec/fixtures/config.ru | 2 +- spec/fixtures/fake_app.rb | 136 +++---- spec/rack/test/cookie_jar_spec.rb | 12 +- spec/rack/test/cookie_object_spec.rb | 68 ++-- spec/rack/test/cookie_spec.rb | 263 ++++++------ spec/rack/test/digest_auth_spec.rb | 30 +- spec/rack/test/multipart_spec.rb | 154 +++---- spec/rack/test/uploaded_file_spec.rb | 28 +- spec/rack/test/utils_spec.rb | 208 +++++----- spec/rack/test_spec.rb | 582 +++++++++++++-------------- spec/spec_helper.rb | 58 ++- spec/support/matchers/challenge.rb | 6 +- 24 files changed, 1027 insertions(+), 973 deletions(-) create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 37dda07a..71278b01 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,4 +1,4 @@ -# Ref: default config +# Ref: default config, with minor tweaks # https://github.com/bbatsov/rubocop/blob/master/config/default.yml AllCops: Include: @@ -11,3 +11,9 @@ AllCops: DisplayCopNames: true DisplayStyleGuide: true ExtraDetails: true + +# Rationale: defalt approach forces us to indent multiline `foo = if bar` statements in an unreasonable way. +Lint/EndAlignment: + EnforcedStyleAlignWith: variable + +inherit_from: .rubocop_todo.yml diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 00000000..911d3276 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,102 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2017-07-12 09:10:37 +0300 using RuboCop version 0.49.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: auto_detection, squiggly, active_support, powerpack, unindent +Layout/IndentHeredoc: + Exclude: + - 'lib/rack/test/utils.rb' + - 'rack-test.gemspec' + +# Offense count: 2 +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Exclude: + - 'lib/rack/test.rb' + +# Offense count: 9 +Metrics/AbcSize: + Max: 58 + +# Offense count: 20 +# Configuration parameters: CountComments, ExcludedMethods. +Metrics/BlockLength: + Max: 455 + +# Offense count: 2 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 166 + +# Offense count: 5 +Metrics/CyclomaticComplexity: + Max: 13 + +# Offense count: 75 +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Metrics/LineLength: + Max: 171 + +# Offense count: 6 +# Configuration parameters: CountComments. +Metrics/MethodLength: + Max: 45 + +# Offense count: 1 +# Configuration parameters: CountComments. +Metrics/ModuleLength: + Max: 124 + +# Offense count: 3 +Metrics/PerceivedComplexity: + Max: 16 + +# Offense count: 1 +Security/Eval: + Exclude: + - 'Thorfile' + +# Offense count: 1 +Style/CaseEquality: + Exclude: + - 'lib/rack/test.rb' + +# Offense count: 4 +Style/Documentation: + Exclude: + - 'spec/**/*' + - 'test/**/*' + - 'Thorfile' + - 'lib/rack/test.rb' + +# Offense count: 2 +Style/IdenticalConditionalBranches: + Exclude: + - 'spec/rack/test/multipart_spec.rb' + +# Offense count: 1 +Style/IfInsideElse: + Exclude: + - 'lib/rack/test/utils.rb' + +# Offense count: 2 +Style/MethodMissing: + Exclude: + - 'lib/rack/test/mock_digest_request.rb' + - 'lib/rack/test/uploaded_file.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, AllowInnerSlashes. +# SupportedStyles: slashes, percent_r, mixed +Style/RegexpLiteral: + Exclude: + - 'lib/rack/test/cookie_jar.rb' diff --git a/Rakefile b/Rakefile index 2786f64d..defccbba 100644 --- a/Rakefile +++ b/Rakefile @@ -1,14 +1,13 @@ -require "rubygems" - +require 'rubygems' require 'rspec/core' -require "rspec/core/rake_task" +require 'rspec/core/rake_task' -task default: :spec +task default: %i[spec rubocop] RSpec::Core::RakeTask.new do |t| - t.pattern = "spec/**/*_spec.rb" - t.ruby_opts = "-w" + t.pattern = 'spec/**/*_spec.rb' + t.ruby_opts = '-w' end require 'rubocop/rake_task' @@ -23,14 +22,14 @@ RuboCop::RakeTask.new # t.rcov_opts = ['-x spec'] # end -desc "Generate RDoc" +desc 'Generate RDoc' task :docs do - FileUtils.rm_rf("doc") - require "rack/test/version" + FileUtils.rm_rf('doc') + require 'rack/test/version' sh "rdoc --title 'Rack::Test #{Rack::Test::VERSION} API Documentation'" end desc 'Removes trailing whitespace' task :whitespace do - sh %{find . -name '*.rb' -exec sed -i 's/ *$//g' {} \\;} + sh %(find . -name '*.rb' -exec sed -i 's/ *$//g' {} \\;) end diff --git a/Thorfile b/Thorfile index 7401e87d..82afb20e 100644 --- a/Thorfile +++ b/Thorfile @@ -1,6 +1,6 @@ module GemHelpers def read_gemspec - @read_gemspec ||= eval(File.read("rack-test.gemspec")) + @read_gemspec ||= eval(File.read('rack-test.gemspec')) end def sh(command) @@ -12,19 +12,19 @@ end class Default < Thor include GemHelpers - desc "build", "Build a rack-test gem" + desc 'build', 'Build a rack-test gem' def build - sh "gem build rack-test.gemspec" - FileUtils.mkdir_p "pkg" - FileUtils.mv read_gemspec.file_name, "pkg" + sh 'gem build rack-test.gemspec' + FileUtils.mkdir_p 'pkg' + FileUtils.mv read_gemspec.file_name, 'pkg' end - desc "install", "Install the latest built gem" + desc 'install', 'Install the latest built gem' def install sh "gem install --local pkg/#{read_gemspec.file_name}" end - desc "release", "Release the current branch to GitHub and RubyGems.org" + desc 'release', 'Release the current branch to GitHub and RubyGems.org' def release build Release.new.tag @@ -35,14 +35,14 @@ end class Release < Thor include GemHelpers - desc "tag", "Tag the gem on the origin server" + desc 'tag', 'Tag the gem on the origin server' def tag release_tag = "v#{read_gemspec.version}" sh "git tag -a #{release_tag} -m 'Tagging #{release_tag}'" sh "git push origin #{release_tag}" end - desc "gem", "Push the gem to RubyGems.org" + desc 'gem', 'Push the gem to RubyGems.org' def gem sh "gem push pkg/#{read_gemspec.file_name}" end diff --git a/lib/rack/mock_session.rb b/lib/rack/mock_session.rb index 9b627314..350c3d69 100644 --- a/lib/rack/mock_session.rb +++ b/lib/rack/mock_session.rb @@ -1,5 +1,4 @@ module Rack - class MockSession # :nodoc: attr_writer :cookie_jar attr_reader :default_host @@ -25,16 +24,16 @@ def set_cookie(cookie, uri = nil) end def request(uri, env) - env["HTTP_COOKIE"] ||= cookie_jar.for(uri) + env['HTTP_COOKIE'] ||= cookie_jar.for(uri) @last_request = Rack::Request.new(env) status, headers, body = @app.call(@last_request.env) - @last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush) + @last_response = MockResponse.new(status, headers, body, env['rack.errors'].flush) body.close if body.respond_to?(:close) - cookie_jar.merge(last_response.headers["Set-Cookie"], uri) + cookie_jar.merge(last_response.headers['Set-Cookie'], uri) - @after_request.each { |hook| hook.call } + @after_request.each(&:call) if @last_response.respond_to?(:finish) @last_response.finish @@ -46,21 +45,19 @@ def request(uri, env) # Return the last request issued in the session. Raises an error if no # requests have been sent yet. def last_request - raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request + raise Rack::Test::Error, 'No request yet. Request a page first.' unless @last_request @last_request end # Return the last response received in the session. Raises an error if # no requests have been sent yet. def last_response - raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response + raise Rack::Test::Error, 'No response yet. Request a page first.' unless @last_response @last_response end def cookie_jar @cookie_jar ||= Rack::Test::CookieJar.new([], @default_host) end - end - end diff --git a/lib/rack/test.rb b/lib/rack/test.rb index 523bb65e..a2fb30db 100644 --- a/lib/rack/test.rb +++ b/lib/rack/test.rb @@ -1,17 +1,17 @@ -require "uri" -require "rack" -require "rack/mock_session" -require "rack/test/cookie_jar" -require "rack/test/mock_digest_request" -require "rack/test/utils" -require "rack/test/methods" -require "rack/test/uploaded_file" -require "rack/test/version" +require 'uri' +require 'rack' +require 'rack/mock_session' +require 'rack/test/cookie_jar' +require 'rack/test/mock_digest_request' +require 'rack/test/utils' +require 'rack/test/methods' +require 'rack/test/uploaded_file' +require 'rack/test/version' module Rack module Test - DEFAULT_HOST = "example.org" - MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1" + DEFAULT_HOST = 'example.org'.freeze + MULTIPART_BOUNDARY = '----------XnJLe9ZIbbGUYtzPQJ16u1'.freeze # The common base class for exceptions raised by Rack::Test class Error < StandardError; end @@ -38,10 +38,10 @@ def initialize(mock_session) @digest_username = nil @digest_password = nil - if mock_session.is_a?(MockSession) - @rack_mock_session = mock_session + @rack_mock_session = if mock_session.is_a?(MockSession) + mock_session else - @rack_mock_session = MockSession.new(mock_session) + MockSession.new(mock_session) end @default_host = @rack_mock_session.default_host @@ -55,7 +55,7 @@ def initialize(mock_session) # Example: # get "/" def get(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "GET", :params => params)) + env = env_for(uri, env.merge(method: 'GET', params: params)) process_request(uri, env, &block) end @@ -64,7 +64,7 @@ def get(uri, params = {}, env = {}, &block) # Example: # post "/signup", "name" => "Bryan" def post(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "POST", :params => params)) + env = env_for(uri, env.merge(method: 'POST', params: params)) process_request(uri, env, &block) end @@ -73,7 +73,7 @@ def post(uri, params = {}, env = {}, &block) # Example: # put "/" def put(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "PUT", :params => params)) + env = env_for(uri, env.merge(method: 'PUT', params: params)) process_request(uri, env, &block) end @@ -82,7 +82,7 @@ def put(uri, params = {}, env = {}, &block) # Example: # patch "/" def patch(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "PATCH", :params => params)) + env = env_for(uri, env.merge(method: 'PATCH', params: params)) process_request(uri, env, &block) end @@ -91,7 +91,7 @@ def patch(uri, params = {}, env = {}, &block) # Example: # delete "/" def delete(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "DELETE", :params => params)) + env = env_for(uri, env.merge(method: 'DELETE', params: params)) process_request(uri, env, &block) end @@ -100,7 +100,7 @@ def delete(uri, params = {}, env = {}, &block) # Example: # options "/" def options(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "OPTIONS", :params => params)) + env = env_for(uri, env.merge(method: 'OPTIONS', params: params)) process_request(uri, env, &block) end @@ -109,7 +109,7 @@ def options(uri, params = {}, env = {}, &block) # Example: # head "/" def head(uri, params = {}, env = {}, &block) - env = env_for(uri, env.merge(:method => "HEAD", :params => params)) + env = env_for(uri, env.merge(method: 'HEAD', params: params)) process_request(uri, env, &block) end @@ -160,11 +160,11 @@ def env(name, value) # Example: # basic_authorize "bryan", "secret" def basic_authorize(username, password) - encoded_login = ["#{username}:#{password}"].pack("m0") + encoded_login = ["#{username}:#{password}"].pack('m0') header('Authorization', "Basic #{encoded_login}") end - alias_method :authorize, :basic_authorize + alias authorize basic_authorize # Set the username and password for HTTP Digest authorization, to be # included in subsequent requests in the HTTP_AUTHORIZATION header. @@ -182,48 +182,48 @@ def digest_authorize(username, password) # a redirect, an error will be raised. def follow_redirect! unless last_response.redirect? - raise Error.new("Last response was not a redirect. Cannot follow_redirect!") + raise Error, 'Last response was not a redirect. Cannot follow_redirect!' end if last_response.status == 307 - send(last_request.request_method.downcase.to_sym, last_response["Location"], last_request.params, { "HTTP_REFERER" => last_request.url }) + send(last_request.request_method.downcase.to_sym, last_response['Location'], last_request.params, 'HTTP_REFERER' => last_request.url) else - get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url }) + get(last_response['Location'], {}, 'HTTP_REFERER' => last_request.url) end end - private + private def env_for(path, env) uri = URI.parse(path) - uri.path = "/#{uri.path}" unless uri.path[0] == ?/ + uri.path = "/#{uri.path}" unless uri.path[0] == '/' uri.host ||= @default_host env = default_env.merge(env) - env["HTTP_HOST"] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(":") + env['HTTP_HOST'] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(':') - env.update("HTTPS" => "on") if URI::HTTPS === uri - env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" if env[:xhr] + env.update('HTTPS' => 'on') if URI::HTTPS === uri + env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' if env[:xhr] # TODO: Remove this after Rack 1.1 has been released. # Stringifying and upcasing methods has be commit upstream - env["REQUEST_METHOD"] ||= env[:method] ? env[:method].to_s.upcase : "GET" + env['REQUEST_METHOD'] ||= env[:method] ? env[:method].to_s.upcase : 'GET' - if ["GET", "DELETE"].include?(env["REQUEST_METHOD"]) + if %w[GET DELETE].include?(env['REQUEST_METHOD']) # merge :params with the query string if params = env[:params] params = parse_nested_query(params) if params.is_a?(String) - uri.query = [uri.query, build_nested_query(params)].compact.reject { |v| v == '' }.join("&") + uri.query = [uri.query, build_nested_query(params)].compact.reject { |v| v == '' }.join('&') end - elsif !env.has_key?(:input) - env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded" + elsif !env.key?(:input) + env['CONTENT_TYPE'] ||= 'application/x-www-form-urlencoded' if env[:params].is_a?(Hash) if data = build_multipart(env[:params]) env[:input] = data - env["CONTENT_LENGTH"] ||= data.length.to_s - env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}" + env['CONTENT_LENGTH'] ||= data.length.to_s + env['CONTENT_TYPE'] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}" else env[:input] = params_to_string(env[:params]) end @@ -234,9 +234,7 @@ def env_for(path, env) env.delete(:params) - if env.has_key?(:cookie) - set_cookie(env.delete(:cookie), uri) - end + set_cookie(env.delete(:cookie), uri) if env.key?(:cookie) Rack::MockRequest.env_for(uri.to_s, env) end @@ -244,15 +242,13 @@ def env_for(path, env) def process_request(uri, env) uri = URI.parse(uri) uri.host ||= @default_host - uri.scheme ||= "https" if env["HTTPS"] == "on" + uri.scheme ||= 'https' if env['HTTPS'] == 'on' @rack_mock_session.request(uri, env) if retry_with_digest_auth?(env) - auth_env = env.merge({ - "HTTP_AUTHORIZATION" => digest_auth_header, - "rack-test.digest_auth_retry" => true - }) + auth_env = env.merge('HTTP_AUTHORIZATION' => digest_auth_header, + 'rack-test.digest_auth_retry' => true) auth_env.delete('rack.request') process_request(uri.path, auth_env) else @@ -263,26 +259,24 @@ def process_request(uri, env) end def digest_auth_header - challenge = last_response["WWW-Authenticate"].split(" ", 2).last + challenge = last_response['WWW-Authenticate'].split(' ', 2).last params = Rack::Auth::Digest::Params.parse(challenge) - params.merge!({ - "username" => @digest_username, - "nc" => "00000001", - "cnonce" => "nonsensenonce", - "uri" => last_request.fullpath, - "method" => last_request.env["REQUEST_METHOD"], - }) + params.merge!('username' => @digest_username, + 'nc' => '00000001', + 'cnonce' => 'nonsensenonce', + 'uri' => last_request.fullpath, + 'method' => last_request.env['REQUEST_METHOD']) - params["response"] = MockDigestRequest.new(params).response(@digest_password) + params['response'] = MockDigestRequest.new(params).response(@digest_password) "Digest #{params}" end def retry_with_digest_auth?(env) last_response.status == 401 && - digest_auth_configured? && - !env["rack-test.digest_auth_retry"] + digest_auth_configured? && + !env['rack-test.digest_auth_retry'] end def digest_auth_configured? @@ -290,15 +284,15 @@ def digest_auth_configured? end def default_env - { "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(@env).merge(headers_for_env) + { 'rack.test' => true, 'REMOTE_ADDR' => '127.0.0.1' }.merge(@env).merge(headers_for_env) end def headers_for_env converted_headers = {} @headers.each do |name, value| - env_key = name.upcase.gsub("-", "_") - env_key = "HTTP_" + env_key unless "CONTENT_TYPE" == env_key + env_key = name.upcase.tr('-', '_') + env_key = 'HTTP_' + env_key unless env_key == 'CONTENT_TYPE' converted_headers[env_key] = value end @@ -308,16 +302,14 @@ def headers_for_env def params_to_string(params) case params when Hash then build_nested_query(params) - when nil then "" + when nil then '' else params end end - end def self.encoding_aware_strings? - defined?(Encoding) && "".respond_to?(:encode) + defined?(Encoding) && ''.respond_to?(:encode) end - end end diff --git a/lib/rack/test/cookie_jar.rb b/lib/rack/test/cookie_jar.rb index c9fe035e..fed13f14 100644 --- a/lib/rack/test/cookie_jar.rb +++ b/lib/rack/test/cookie_jar.rb @@ -1,9 +1,8 @@ -require "uri" -require "time" +require 'uri' +require 'time' module Rack module Test - class Cookie # :nodoc: include Rack::Utils @@ -21,8 +20,8 @@ def initialize(raw, uri = nil, default_host = DEFAULT_HOST) @name, @value = parse_query(@name_value_raw, ';').to_a.first @options = parse_query(options, ';') - @options["domain"] ||= (uri.host || default_host) - @options["path"] ||= uri.path.sub(/\/[^\/]*\Z/, "") + @options['domain'] ||= (uri.host || default_host) + @options['path'] ||= uri.path.sub(/\/[^\/]*\Z/, '') end def replaces?(other) @@ -41,25 +40,25 @@ def empty? # :api: private def domain - @options["domain"] + @options['domain'] end def secure? - @options.has_key?("secure") + @options.key?('secure') end def http_only? - @options.has_key?('HttpOnly') + @options.key?('HttpOnly') end # :api: private def path - @options["path"].strip || "/" + @options['path'].strip || '/' end # :api: private def expires - Time.parse(@options["expires"]) if @options["expires"] + Time.parse(@options['expires']) if @options['expires'] end # :api: private @@ -71,19 +70,17 @@ def expired? def valid?(uri) uri ||= default_uri - if uri.host.nil? - uri.host = @default_host - end + uri.host = @default_host if uri.host.nil? real_domain = domain =~ /^\./ ? domain[1..-1] : domain - (!secure? || (secure? && uri.scheme == "https")) && - uri.host =~ Regexp.new("#{Regexp.escape(real_domain)}$", Regexp::IGNORECASE) && - uri.path =~ Regexp.new("^#{Regexp.escape(path)}") + (!secure? || (secure? && uri.scheme == 'https')) && + uri.host =~ Regexp.new("#{Regexp.escape(real_domain)}$", Regexp::IGNORECASE) && + uri.path =~ Regexp.new("^#{Regexp.escape(path)}") end # :api: private def matches?(uri) - ! expired? && valid?(uri) + !expired? && valid?(uri) end # :api: private @@ -91,25 +88,24 @@ def <=>(other) # Orders the cookies from least specific to most [name, path, domain.reverse] <=> [other.name, other.path, other.domain.reverse] end + def to_h @options.merge( 'value' => @value, 'HttpOnly' => http_only?, - 'secure' => secure?, + 'secure' => secure? ) end - alias_method :to_hash, :to_h + alias to_hash to_h - protected + protected def default_uri - URI.parse("//" + @default_host + "/") + URI.parse('//' + @default_host + '/') end - end class CookieJar # :nodoc: - # :api: private def initialize(cookies = [], default_host = DEFAULT_HOST) @default_host = default_host @@ -128,7 +124,7 @@ def []=(name, value) end def get_cookie(name) - hash_for(nil).fetch(name,nil) + hash_for(nil).fetch(name, nil) end def delete(name) @@ -142,7 +138,7 @@ def merge(raw_cookies, uri = nil) if raw_cookies.is_a? String raw_cookies = raw_cookies.split("\n") - raw_cookies.reject!{|c| c.empty? } + raw_cookies.reject!(&:empty?) end raw_cookies.each do |raw_cookie| @@ -162,7 +158,7 @@ def <<(new_cookie) # :api: private def for(uri) - hash_for(uri).values.map { |c| c.raw }.join(';') + hash_for(uri).values.map(&:raw).join(';') end def to_hash @@ -172,10 +168,10 @@ def to_hash cookies[name] = cookie.value end - return cookies + cookies end - protected + protected def hash_for(uri = nil) cookies = {} @@ -189,10 +185,8 @@ def hash_for(uri = nil) cookies[cookie.name] = cookie if !uri || cookie.matches?(uri) end - return cookies + cookies end - end - end end diff --git a/lib/rack/test/methods.rb b/lib/rack/test/methods.rb index 8e87af0f..7204dbbb 100644 --- a/lib/rack/test/methods.rb +++ b/lib/rack/test/methods.rb @@ -1,8 +1,7 @@ -require "forwardable" +require 'forwardable' module Rack module Test - # This module serves as the primary integration point for using Rack::Test # in a testing environment. It depends on an app method being defined in the # same context, and provides the Rack::Test API methods (see Rack::Test::Session @@ -56,26 +55,26 @@ def _current_session_names # :nodoc: @_current_session_names ||= [:default] end - METHODS = [ - :request, - :get, - :post, - :put, - :patch, - :delete, - :options, - :head, - :follow_redirect!, - :header, - :env, - :set_cookie, - :clear_cookies, - :authorize, - :basic_authorize, - :digest_authorize, - :last_response, - :last_request - ] + METHODS = %i[ + request + get + post + put + patch + delete + options + head + follow_redirect! + header + env + set_cookie + clear_cookies + authorize + basic_authorize + digest_authorize + last_response + last_request + ].freeze def_delegators :current_session, *METHODS end diff --git a/lib/rack/test/mock_digest_request.rb b/lib/rack/test/mock_digest_request.rb index b5764930..bda24ff1 100644 --- a/lib/rack/test/mock_digest_request.rb +++ b/lib/rack/test/mock_digest_request.rb @@ -1,14 +1,12 @@ module Rack module Test - class MockDigestRequest # :nodoc: - def initialize(params) @params = params end def method_missing(sym) - if @params.has_key? k = sym.to_s + if @params.key? k = sym.to_s return @params[k] end @@ -22,8 +20,6 @@ def method def response(password) Rack::Auth::Digest::MD5.new(nil).send :digest, self, password end - end - end end diff --git a/lib/rack/test/uploaded_file.rb b/lib/rack/test/uploaded_file.rb index 67cdfa10..7ee09b29 100644 --- a/lib/rack/test/uploaded_file.rb +++ b/lib/rack/test/uploaded_file.rb @@ -1,16 +1,14 @@ -require "tempfile" -require "fileutils" +require 'tempfile' +require 'fileutils' module Rack module Test - # Wraps a Tempfile with a content type. Including one or more UploadedFile's # in the params causes Rack::Test to build and issue a multipart request. # # Example: # post "/photos", "file" => Rack::Test::UploadedFile.new("me.jpg", "image/jpeg") class UploadedFile - # The filename, *not* including the path, of the "uploaded" file attr_reader :original_filename @@ -20,7 +18,7 @@ class UploadedFile # The content type of the "uploaded" file attr_accessor :content_type - def initialize(path, content_type = "text/plain", binary = false) + def initialize(path, content_type = 'text/plain', binary = false) raise "#{path} file does not exist" unless ::File.exist?(path) @content_type = content_type @@ -39,7 +37,7 @@ def path @tempfile.path end - alias_method :local_path, :path + alias local_path path def method_missing(method_name, *args, &block) #:nodoc: @tempfile.__send__(method_name, *args, &block) @@ -57,8 +55,6 @@ def self.actually_finalize(file) file.close file.unlink end - end - end end diff --git a/lib/rack/test/utils.rb b/lib/rack/test/utils.rb index 0f02ef44..076a7825 100644 --- a/lib/rack/test/utils.rb +++ b/lib/rack/test/utils.rb @@ -1,6 +1,5 @@ module Rack module Test - module Utils # :nodoc: include Rack::Utils extend Rack::Utils @@ -12,16 +11,14 @@ def build_nested_query(value, prefix = nil) "#{prefix}[]=" else value.map do |v| - unless unescape(prefix) =~ /\[\]$/ - prefix = "#{prefix}[]" - end - build_nested_query(v, "#{prefix}") - end.join("&") + prefix = "#{prefix}[]" unless unescape(prefix) =~ /\[\]$/ + build_nested_query(v, prefix.to_s) + end.join('&') end when Hash value.map do |k, v| build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k)) - end.join("&") + end.join('&') when NilClass prefix.to_s else @@ -32,9 +29,7 @@ def build_nested_query(value, prefix = nil) def build_multipart(params, first = true, multipart = false) if first - unless params.is_a?(Hash) - raise ArgumentError, "value must be a Hash" - end + raise ArgumentError, 'value must be a Hash' unless params.is_a?(Hash) query = lambda { |value| case value @@ -50,7 +45,7 @@ def build_multipart(params, first = true, multipart = false) return nil unless multipart end - flattened_params = Hash.new + flattened_params = {} params.each do |key, value| k = first ? key.to_s : "[#{key}]" @@ -58,23 +53,21 @@ def build_multipart(params, first = true, multipart = false) case value when Array value.map do |v| - - if (v.is_a?(Hash)) + if v.is_a?(Hash) nested_params = {} - build_multipart(v, false).each { |subkey, subvalue| + build_multipart(v, false).each do |subkey, subvalue| nested_params[subkey] = subvalue - } + end flattened_params["#{k}[]"] ||= [] flattened_params["#{k}[]"] << nested_params else flattened_params["#{k}[]"] = value end - end when Hash - build_multipart(value, false).each { |subkey, subvalue| + build_multipart(value, false).each do |subkey, subvalue| flattened_params[k + subkey] = subvalue - } + end else flattened_params[k] = value end @@ -89,24 +82,25 @@ def build_multipart(params, first = true, multipart = false) module_function :build_multipart private + def build_parts(parameters) get_parts(parameters).join + "--#{MULTIPART_BOUNDARY}--\r" end module_function :build_parts def get_parts(parameters) - parameters.map { |name, value| - if name =~ /\[\]\Z/ && value.is_a?(Array) && value.all? {|v| v.is_a?(Hash)} - value.map { |hash| + parameters.map do |name, value| + if name =~ /\[\]\Z/ && value.is_a?(Array) && value.all? { |v| v.is_a?(Hash) } + value.map do |hash| new_value = {} - hash.each { |k, v| new_value[name+k] = v } + hash.each { |k, v| new_value[name + k] = v } get_parts(new_value).join - }.join + end.join else if value.respond_to?(:original_filename) build_file_part(name, value) - elsif value.is_a?(Array) and value.all? { |v| v.respond_to?(:original_filename) } + elsif value.is_a?(Array) && value.all? { |v| v.respond_to?(:original_filename) } value.map do |v| build_file_part(name, v) end.join @@ -116,14 +110,12 @@ def get_parts(parameters) Rack::Test.encoding_aware_strings? ? primitive_part.force_encoding('BINARY') : primitive_part end end - } + end end module_function :get_parts def build_primitive_part(parameter_name, value) - unless value.is_a? Array - value = [value] - end + value = [value] unless value.is_a? Array value.map do |v| <<-EOF --#{MULTIPART_BOUNDARY}\r @@ -136,7 +128,7 @@ def build_primitive_part(parameter_name, value) module_function :build_primitive_part def build_file_part(parameter_name, uploaded_file) - ::File.open(uploaded_file.path, "rb") do |physical_file| + ::File.open(uploaded_file.path, 'rb') do |physical_file| physical_file.set_encoding(Encoding::BINARY) if physical_file.respond_to?(:set_encoding) <<-EOF --#{MULTIPART_BOUNDARY}\r @@ -149,8 +141,6 @@ def build_file_part(parameter_name, uploaded_file) end end module_function :build_file_part - end - end end diff --git a/rack-test.gemspec b/rack-test.gemspec index 8a25806e..87bba38f 100644 --- a/rack-test.gemspec +++ b/rack-test.gemspec @@ -21,7 +21,7 @@ request helpers feature. s.require_paths = ['lib'] s.files = `git ls-files -- lib/*`.split("\n") + %w[History.md MIT-LICENSE.txt README.md] - s.required_ruby_version = ">= 2.2.2" + s.required_ruby_version = '>= 2.2.2' s.add_dependency 'rack', '>= 1.0', '< 3' s.add_development_dependency 'rake', '~> 12.0' s.add_development_dependency 'rspec', '~> 3.6' diff --git a/spec/fixtures/config.ru b/spec/fixtures/config.ru index 407c9b94..52a7cfa7 100644 --- a/spec/fixtures/config.ru +++ b/spec/fixtures/config.ru @@ -1,3 +1,3 @@ -require "fake_app" +require 'fake_app' run Rack::Test::FakeApp diff --git a/spec/fixtures/fake_app.rb b/spec/fixtures/fake_app.rb index b21a47ca..9e7f02c7 100644 --- a/spec/fixtures/fake_app.rb +++ b/spec/fixtures/fake_app.rb @@ -1,154 +1,148 @@ -require "rubygems" -require "sinatra/base" +require 'rubygems' +require 'sinatra/base' module Rack module Test - class FakeApp < Sinatra::Base - head "/" do - "meh" + head '/' do + 'meh' end - options "/" do - [200, {}, ""] + options '/' do + [200, {}, ''] end - get "/" do + get '/' do "Hello, GET: #{params.inspect}" end - get "/redirect" do - redirect "/redirected" + get '/redirect' do + redirect '/redirected' end - post "/redirect" do - if params["status"] - redirect to("/redirected"), Integer(params["status"]) + post '/redirect' do + if params['status'] + redirect to('/redirected'), Integer(params['status']) else - redirect "/redirected" + redirect '/redirected' end end - [:get, :put, :post, :delete].each do |meth| - send(meth, "/redirected") do - additional_info = (meth == :get) ? "" : " using #{meth} with #{params}" + %i[get put post delete].each do |meth| + send(meth, '/redirected') do + additional_info = meth == :get ? '' : " using #{meth} with #{params}" "You've been redirected" + additional_info end end - get "/void" do - [200, {}, ""] + get '/void' do + [200, {}, ''] end - get "/cookies/show" do + get '/cookies/show' do request.cookies.inspect end - get "/COOKIES/show" do + get '/COOKIES/show' do request.cookies.inspect end - get "/not-cookies/show" do + get '/not-cookies/show' do request.cookies.inspect end - get "/cookies/set-secure" do - raise if params["value"].nil? + get '/cookies/set-secure' do + raise if params['value'].nil? - response.set_cookie("secure-cookie", :value => params["value"], :secure => true) - "Set" + response.set_cookie('secure-cookie', value: params['value'], secure: true) + 'Set' end - get "/cookies/set-simple" do - raise if params["value"].nil? + get '/cookies/set-simple' do + raise if params['value'].nil? - response.set_cookie "simple", params["value"] - "Set" + response.set_cookie 'simple', params['value'] + 'Set' end - post "/cookies/default-path" do - raise if params["value"].nil? + post '/cookies/default-path' do + raise if params['value'].nil? - response.set_cookie "simple", params["value"] - "Set" + response.set_cookie 'simple', params['value'] + 'Set' end - get "/cookies/default-path" do + get '/cookies/default-path' do response.cookies.inspect end - get "/cookies/delete" do - response.delete_cookie "value" + get '/cookies/delete' do + response.delete_cookie 'value' end - get "/cookies/count" do - old_value = request.cookies["count"].to_i || 0 + get '/cookies/count' do + old_value = request.cookies['count'].to_i || 0 new_value = (old_value + 1).to_s - response.set_cookie("count", :value => new_value) + response.set_cookie('count', value: new_value) new_value end - get "/cookies/set" do - raise if params["value"].nil? + get '/cookies/set' do + raise if params['value'].nil? - response.set_cookie("value", { - :value => params["value"], - :path => "/cookies", - :expires => Time.now + 10 - }) - "Set" + response.set_cookie('value', value: params['value'], + path: '/cookies', + expires: Time.now + 10) + 'Set' end - get "/cookies/domain" do - old_value = request.cookies["count"].to_i || 0 + get '/cookies/domain' do + old_value = request.cookies['count'].to_i || 0 new_value = (old_value + 1).to_s - response.set_cookie("count", :value => new_value, :domain => "localhost.com") + response.set_cookie('count', value: new_value, domain: 'localhost.com') new_value end - get "/cookies/subdomain" do - old_value = request.cookies["count"].to_i || 0 + get '/cookies/subdomain' do + old_value = request.cookies['count'].to_i || 0 new_value = (old_value + 1).to_s - response.set_cookie("count", :value => new_value, :domain => ".example.org") + response.set_cookie('count', value: new_value, domain: '.example.org') new_value end - get "/cookies/set-uppercase" do - raise if params["value"].nil? + get '/cookies/set-uppercase' do + raise if params['value'].nil? - response.set_cookie("VALUE", { - :value => params["value"], - :path => "/cookies", - :expires => Time.now + 10 - }) - "Set" + response.set_cookie('VALUE', value: params['value'], + path: '/cookies', + expires: Time.now + 10) + 'Set' end - get "/cookies/set-multiple" do - response.set_cookie("key1", :value => "value1") - response.set_cookie("key2", :value => "value2") - "Set" + get '/cookies/set-multiple' do + response.set_cookie('key1', value: 'value1') + response.set_cookie('key2', value: 'value2') + 'Set' end - post "/" do + post '/' do "Hello, POST: #{params.inspect}" end - put "/" do + put '/' do "Hello, PUT: #{params.inspect}" end - patch "/" do + patch '/' do "Hello, PUT: #{params.inspect}" end - delete "/" do + delete '/' do "Hello, DELETE: #{params.inspect}" end end - end end diff --git a/spec/rack/test/cookie_jar_spec.rb b/spec/rack/test/cookie_jar_spec.rb index 90efd2a1..6ee2ac6a 100644 --- a/spec/rack/test/cookie_jar_spec.rb +++ b/spec/rack/test/cookie_jar_spec.rb @@ -1,18 +1,18 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::CookieJar do subject(:jar) { Rack::Test::CookieJar.new } - describe "#get_cookie" do - context "with a populated jar" do - let(:cookie_value) { "foo;abc" } - let(:cookie_name) { "a_cookie_name" } + describe '#get_cookie' do + context 'with a populated jar' do + let(:cookie_value) { 'foo;abc' } + let(:cookie_name) { 'a_cookie_name' } before do jar[cookie_name] = cookie_value end - it "returns full cookie objects" do + it 'returns full cookie objects' do cookie = jar.get_cookie(cookie_name) expect(cookie).to be_a(Rack::Test::Cookie) end diff --git a/spec/rack/test/cookie_object_spec.rb b/spec/rack/test/cookie_object_spec.rb index f08b8277..9617d555 100644 --- a/spec/rack/test/cookie_object_spec.rb +++ b/spec/rack/test/cookie_object_spec.rb @@ -1,64 +1,64 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::Cookie do subject(:cookie) { Rack::Test::Cookie.new(cookie_string) } let(:cookie_string) { raw_cookie_string } - let(:raw_cookie_string) { + let(:raw_cookie_string) do [ - "cookie_name=" + CGI.escape(value), - "domain=" + domain, - "path=" + path, - "expires=" + expires, - ].join("; ") - } + 'cookie_name=' + CGI.escape(value), + 'domain=' + domain, + 'path=' + path, + 'expires=' + expires + ].join('; ') + end - let(:http_only_raw_cookie_string) { - raw_cookie_string + "; HttpOnly" - } + let(:http_only_raw_cookie_string) do + raw_cookie_string + '; HttpOnly' + end - let(:http_only_secure_raw_cookie_string) { - http_only_raw_cookie_string + "; secure" - } + let(:http_only_secure_raw_cookie_string) do + http_only_raw_cookie_string + '; secure' + end - let(:value) { "the cookie value" } - let(:domain) { "www.example.org" } - let(:path) { "/" } - let(:expires) { "Mon, 10 Aug 2015 14:40:57 0100" } + let(:value) { 'the cookie value' } + let(:domain) { 'www.example.org' } + let(:path) { '/' } + let(:expires) { 'Mon, 10 Aug 2015 14:40:57 0100' } - describe "#to_h" do + describe '#to_h' do let(:cookie_string) { http_only_secure_raw_cookie_string } - it "returns the cookie value and all options" do + it 'returns the cookie value and all options' do expect(cookie.to_h).to eq( - "value" => value, - "domain" => domain, - "path" => path, - "expires" => expires, - "HttpOnly" => true, - "secure" => true, - ) + 'value' => value, + 'domain' => domain, + 'path' => path, + 'expires' => expires, + 'HttpOnly' => true, + 'secure' => true + ) end end - describe "#to_hash" do - it "is an alias for #to_h" do + describe '#to_hash' do + it 'is an alias for #to_h' do expect(cookie.to_hash).to eq(cookie.to_h) end end - describe "#http_only?" do - context "for a non HTTP only cookie" do - it "returns false" do + describe '#http_only?' do + context 'for a non HTTP only cookie' do + it 'returns false' do expect(cookie.http_only?).to be(false) end end - context "for a HTTP only cookie" do + context 'for a HTTP only cookie' do let(:cookie_string) { http_only_raw_cookie_string } - it "returns true" do + it 'returns true' do expect(cookie.http_only?).to be(true) end end diff --git a/spec/rack/test/cookie_spec.rb b/spec/rack/test/cookie_spec.rb index 0b8a623f..6b35c25a 100644 --- a/spec/rack/test/cookie_spec.rb +++ b/spec/rack/test/cookie_spec.rb @@ -1,233 +1,232 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::Session do - - context "cookies" do - it "keeps a cookie jar" do - get "/cookies/show" + context 'cookies' do + it 'keeps a cookie jar' do + get '/cookies/show' check expect(last_request.cookies).to eq({}) - get "/cookies/set", "value" => "1" - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "1" }) + get '/cookies/set', 'value' => '1' + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '1') end it "doesn't send expired cookies" do - get "/cookies/set", "value" => "1" + get '/cookies/set', 'value' => '1' now = Time.now - allow(Time).to receive_messages(:now => now + 60) - get "/cookies/show" + allow(Time).to receive_messages(now: now + 60) + get '/cookies/show' expect(last_request.cookies).to eq({}) end - it "cookie path defaults to the uri of the document that was requested" do - skip "See issue rack-test github issue #50" - post "/cookies/default-path", "value" => "cookie" - get "/cookies/default-path" - expect(last_request.cookies).to eq({ "simple"=>"cookie" }) - get "/cookies/show" + it 'cookie path defaults to the uri of the document that was requested' do + skip 'See issue rack-test github issue #50' + post '/cookies/default-path', 'value' => 'cookie' + get '/cookies/default-path' + expect(last_request.cookies).to eq('simple' => 'cookie') + get '/cookies/show' expect(last_request.cookies).to eq({}) end - it "escapes cookie values" do + it 'escapes cookie values' do jar = Rack::Test::CookieJar.new - jar["value"] = "foo;abc" - expect(jar["value"]).to eq("foo;abc") + jar['value'] = 'foo;abc' + expect(jar['value']).to eq('foo;abc') end - it "deletes cookies directly from the CookieJar" do + it 'deletes cookies directly from the CookieJar' do jar = Rack::Test::CookieJar.new - jar["abcd"] = "1234" - expect(jar["abcd"]).to eq("1234") - jar.delete("abcd") - expect(jar["abcd"]).to eq(nil) + jar['abcd'] = '1234' + expect(jar['abcd']).to eq('1234') + jar.delete('abcd') + expect(jar['abcd']).to eq(nil) end - it "allow symbol access" do + it 'allow symbol access' do jar = Rack::Test::CookieJar.new - jar["value"] = "foo;abc" - jar[:value].should == "foo;abc" + jar['value'] = 'foo;abc' + jar[:value].should == 'foo;abc' end it "doesn't send cookies with the wrong domain" do - get "http://www.example.com/cookies/set", "value" => "1" - get "http://www.other.example/cookies/show" + get 'http://www.example.com/cookies/set', 'value' => '1' + get 'http://www.other.example/cookies/show' expect(last_request.cookies).to eq({}) end it "doesn't send cookies with the wrong path" do - get "/cookies/set", "value" => "1" - get "/not-cookies/show" + get '/cookies/set', 'value' => '1' + get '/not-cookies/show' expect(last_request.cookies).to eq({}) end it "persists cookies across requests that don't return any cookie headers" do - get "/cookies/set", "value" => "1" - get "/void" - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "1" }) + get '/cookies/set', 'value' => '1' + get '/void' + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '1') end - it "deletes cookies" do - get "/cookies/set", "value" => "1" - get "/cookies/delete" - get "/cookies/show" - expect(last_request.cookies).to eq({ }) + it 'deletes cookies' do + get '/cookies/set', 'value' => '1' + get '/cookies/delete' + get '/cookies/show' + expect(last_request.cookies).to eq({}) end - it "respects cookie domains when no domain is explicitly set" do - skip "FIXME: www.example.org should not get the first cookie" - expect(request("http://example.org/cookies/count")).to have_body("1") - expect(request("http://www.example.org/cookies/count")).to have_body("1") - expect(request("http://example.org/cookies/count")).to have_body("2") - expect(request("http://www.example.org/cookies/count")).to have_body("2") + it 'respects cookie domains when no domain is explicitly set' do + skip 'FIXME: www.example.org should not get the first cookie' + expect(request('http://example.org/cookies/count')).to have_body('1') + expect(request('http://www.example.org/cookies/count')).to have_body('1') + expect(request('http://example.org/cookies/count')).to have_body('2') + expect(request('http://www.example.org/cookies/count')).to have_body('2') end - it "treats domains case insensitively" do - get "http://example.com/cookies/set", "value" => "1" - get "http://EXAMPLE.COM/cookies/show" - expect(last_request.cookies).to eq({ "value" => "1" }) + it 'treats domains case insensitively' do + get 'http://example.com/cookies/set', 'value' => '1' + get 'http://EXAMPLE.COM/cookies/show' + expect(last_request.cookies).to eq('value' => '1') end - it "treats paths case sensitively" do - get "/cookies/set", "value" => "1" - get "/COOKIES/show" + it 'treats paths case sensitively' do + get '/cookies/set', 'value' => '1' + get '/COOKIES/show' expect(last_request.cookies).to eq({}) end - it "prefers more specific cookies" do - get "http://example.com/cookies/set", "value" => "domain" - get "http://sub.example.com/cookies/set", "value" => "sub" + it 'prefers more specific cookies' do + get 'http://example.com/cookies/set', 'value' => 'domain' + get 'http://sub.example.com/cookies/set', 'value' => 'sub' - get "http://sub.example.com/cookies/show" - check expect(last_request.cookies).to eq({ "value" => "sub" }) + get 'http://sub.example.com/cookies/show' + check expect(last_request.cookies).to eq('value' => 'sub') - get "http://example.com/cookies/show" - expect(last_request.cookies).to eq({ "value" => "domain" }) + get 'http://example.com/cookies/show' + expect(last_request.cookies).to eq('value' => 'domain') end - it "treats cookie names case insensitively" do - get "/cookies/set", "value" => "lowercase" - get "/cookies/set-uppercase", "value" => "UPPERCASE" - get "/cookies/show" - expect(last_request.cookies).to eq({ "VALUE" => "UPPERCASE" }) + it 'treats cookie names case insensitively' do + get '/cookies/set', 'value' => 'lowercase' + get '/cookies/set-uppercase', 'value' => 'UPPERCASE' + get '/cookies/show' + expect(last_request.cookies).to eq('VALUE' => 'UPPERCASE') end - it "defaults the domain to the request domain" do - get "http://example.com/cookies/set-simple", "value" => "cookie" - get "http://example.com/cookies/show" - check expect(last_request.cookies).to eq({ "simple" => "cookie" }) + it 'defaults the domain to the request domain' do + get 'http://example.com/cookies/set-simple', 'value' => 'cookie' + get 'http://example.com/cookies/show' + check expect(last_request.cookies).to eq('simple' => 'cookie') - get "http://other.example/cookies/show" + get 'http://other.example/cookies/show' expect(last_request.cookies).to eq({}) end - it "defaults the domain to the request path up to the last slash" do - get "/cookies/set-simple", "value" => "1" - get "/not-cookies/show" + it 'defaults the domain to the request path up to the last slash' do + get '/cookies/set-simple', 'value' => '1' + get '/not-cookies/show' expect(last_request.cookies).to eq({}) end - it "supports secure cookies" do - get "https://example.com/cookies/set-secure", "value" => "set" - get "http://example.com/cookies/show" + it 'supports secure cookies' do + get 'https://example.com/cookies/set-secure', 'value' => 'set' + get 'http://example.com/cookies/show' check expect(last_request.cookies).to eq({}) - get "https://example.com/cookies/show" - expect(last_request.cookies).to eq({ "secure-cookie" => "set" }) + get 'https://example.com/cookies/show' + expect(last_request.cookies).to eq('secure-cookie' => 'set') expect(rack_mock_session.cookie_jar['secure-cookie']).to eq('set') end - it "supports secure cookies when enabling SSL via env" do - get "//example.com/cookies/set-secure", { "value" => "set" }, "HTTPS" => "on" - get "//example.com/cookies/show", nil, "HTTPS" => "off" + it 'supports secure cookies when enabling SSL via env' do + get '//example.com/cookies/set-secure', { 'value' => 'set' }, 'HTTPS' => 'on' + get '//example.com/cookies/show', nil, 'HTTPS' => 'off' check expect(last_request.cookies).to eq({}) - get "//example.com/cookies/show", nil, "HTTPS" => "on" - expect(last_request.cookies).to eq({ "secure-cookie" => "set" }) + get '//example.com/cookies/show', nil, 'HTTPS' => 'on' + expect(last_request.cookies).to eq('secure-cookie' => 'set') expect(rack_mock_session.cookie_jar['secure-cookie']).to eq('set') end - it "keeps separate cookie jars for different domains" do - get "http://example.com/cookies/set", "value" => "example" - get "http://example.com/cookies/show" - check expect(last_request.cookies).to eq({ "value" => "example" }) + it 'keeps separate cookie jars for different domains' do + get 'http://example.com/cookies/set', 'value' => 'example' + get 'http://example.com/cookies/show' + check expect(last_request.cookies).to eq('value' => 'example') - get "http://other.example/cookies/set", "value" => "other" - get "http://other.example/cookies/show" - check expect(last_request.cookies).to eq({ "value" => "other" }) + get 'http://other.example/cookies/set', 'value' => 'other' + get 'http://other.example/cookies/show' + check expect(last_request.cookies).to eq('value' => 'other') - get "http://example.com/cookies/show" - expect(last_request.cookies).to eq({ "value" => "example" }) + get 'http://example.com/cookies/show' + expect(last_request.cookies).to eq('value' => 'example') end - it "keeps one cookie jar for domain and its subdomains" do - get "http://example.org/cookies/subdomain" - get "http://example.org/cookies/subdomain" - expect(last_request.cookies).to eq({ "count" => "1" }) + it 'keeps one cookie jar for domain and its subdomains' do + get 'http://example.org/cookies/subdomain' + get 'http://example.org/cookies/subdomain' + expect(last_request.cookies).to eq('count' => '1') - get "http://foo.example.org/cookies/subdomain" - expect(last_request.cookies).to eq({ "count" => "2" }) + get 'http://foo.example.org/cookies/subdomain' + expect(last_request.cookies).to eq('count' => '2') end - it "allows cookies to be cleared" do - get "/cookies/set", "value" => "1" + it 'allows cookies to be cleared' do + get '/cookies/set', 'value' => '1' clear_cookies - get "/cookies/show" + get '/cookies/show' expect(last_request.cookies).to eq({}) end - it "allow cookies to be set" do - set_cookie "value=10" - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "10" }) + it 'allow cookies to be set' do + set_cookie 'value=10' + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '10') end - it "allows an array of cookies to be set" do - set_cookie ["value=10", "foo=bar"] - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "10", "foo" => "bar" }) + it 'allows an array of cookies to be set' do + set_cookie ['value=10', 'foo=bar'] + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '10', 'foo' => 'bar') end - it "skips emtpy string cookies" do + it 'skips emtpy string cookies' do set_cookie "value=10\n\nfoo=bar" - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "10", "foo" => "bar" }) + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '10', 'foo' => 'bar') end - it "parses multiple cookies properly" do - get "/cookies/set-multiple" - get "/cookies/show" - expect(last_request.cookies).to eq({ "key1" => "value1", "key2" => "value2" }) + it 'parses multiple cookies properly' do + get '/cookies/set-multiple' + get '/cookies/show' + expect(last_request.cookies).to eq('key1' => 'value1', 'key2' => 'value2') end - it "supports multiple sessions" do + it 'supports multiple sessions' do with_session(:first) do - get "/cookies/set", "value" => "1" - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "1" }) + get '/cookies/set', 'value' => '1' + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '1') end with_session(:second) do - get "/cookies/show" - expect(last_request.cookies).to eq({ }) + get '/cookies/show' + expect(last_request.cookies).to eq({}) end end - it "uses :default as the default session name" do - get "/cookies/set", "value" => "1" - get "/cookies/show" - check expect(last_request.cookies).to eq({ "value" => "1" }) + it 'uses :default as the default session name' do + get '/cookies/set', 'value' => '1' + get '/cookies/show' + check expect(last_request.cookies).to eq('value' => '1') with_session(:default) do - get "/cookies/show" - expect(last_request.cookies).to eq({ "value" => "1" }) + get '/cookies/show' + expect(last_request.cookies).to eq('value' => '1') end end - it "accepts explicitly provided cookies" do - request "/cookies/show", :cookie => "value=1" - expect(last_request.cookies).to eq({ "value" => "1" }) + it 'accepts explicitly provided cookies' do + request '/cookies/show', cookie: 'value=1' + expect(last_request.cookies).to eq('value' => '1') end end end diff --git a/spec/rack/test/digest_auth_spec.rb b/spec/rack/test/digest_auth_spec.rb index cccf1d6e..6fbfc04c 100644 --- a/spec/rack/test/digest_auth_spec.rb +++ b/spec/rack/test/digest_auth_spec.rb @@ -1,8 +1,7 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::Session do - context "HTTP Digest authentication" do - + context 'HTTP Digest authentication' do def app app = Rack::Auth::Digest::MD5.new(Rack::Test::FakeApp.new) do |username| { 'alice' => 'correct-password' }[username] @@ -18,29 +17,28 @@ def app expect(last_response).to be_challenge end - it "correctly authenticates GETs" do - digest_authorize "alice", "correct-password" - response = get "/" + it 'correctly authenticates GETs' do + digest_authorize 'alice', 'correct-password' + response = get '/' expect(response).to be_ok end - it "correctly authenticates GETs with params" do - digest_authorize "alice", "correct-password" - response = get "/", "foo" => "bar" + it 'correctly authenticates GETs with params' do + digest_authorize 'alice', 'correct-password' + response = get '/', 'foo' => 'bar' expect(response).to be_ok end - it "correctly authenticates POSTs" do - digest_authorize "alice", "correct-password" - response = post "/" + it 'correctly authenticates POSTs' do + digest_authorize 'alice', 'correct-password' + response = post '/' expect(response).to be_ok end - it "returns a re-challenge if authenticating incorrectly" do - digest_authorize "alice", "incorrect-password" - response = get "/" + it 'returns a re-challenge if authenticating incorrectly' do + digest_authorize 'alice', 'incorrect-password' + response = get '/' expect(response).to be_challenge end - end end diff --git a/spec/rack/test/multipart_spec.rb b/spec/rack/test/multipart_spec.rb index 2e7bf165..6968d257 100644 --- a/spec/rack/test/multipart_spec.rb +++ b/spec/rack/test/multipart_spec.rb @@ -1,15 +1,14 @@ # encoding: UTF-8 -require "spec_helper" +require 'spec_helper' describe Rack::Test::Session do - def test_file_path - File.dirname(__FILE__) + "/../../fixtures/foo.txt" + File.dirname(__FILE__) + '/../../fixtures/foo.txt' end def second_test_file_path - File.dirname(__FILE__) + "/../../fixtures/bar.txt" + File.dirname(__FILE__) + '/../../fixtures/bar.txt' end def uploaded_file @@ -20,126 +19,127 @@ def second_uploaded_file Rack::Test::UploadedFile.new(second_test_file_path) end - context "uploading a file" do - it "sends the multipart/form-data content type" do - post "/", "photo" => uploaded_file - expect(last_request.env["CONTENT_TYPE"]).to include("multipart/form-data;") + context 'uploading a file' do + it 'sends the multipart/form-data content type' do + post '/', 'photo' => uploaded_file + expect(last_request.env['CONTENT_TYPE']).to include('multipart/form-data;') end - it "sends regular params" do - post "/", "photo" => uploaded_file, "foo" => "bar" - expect(last_request.POST["foo"]).to eq("bar") + it 'sends regular params' do + post '/', 'photo' => uploaded_file, 'foo' => 'bar' + expect(last_request.POST['foo']).to eq('bar') end - it "sends nested params" do - post "/", "photo" => uploaded_file, "foo" => {"bar" => "baz"} - expect(last_request.POST["foo"]["bar"]).to eq("baz") + it 'sends nested params' do + post '/', 'photo' => uploaded_file, 'foo' => { 'bar' => 'baz' } + expect(last_request.POST['foo']['bar']).to eq('baz') end - it "sends multiple nested params" do - post "/", "photo" => uploaded_file, "foo" => {"bar" => {"baz" => "bop"}} - expect(last_request.POST["foo"]["bar"]["baz"]).to eq("bop") + it 'sends multiple nested params' do + post '/', 'photo' => uploaded_file, 'foo' => { 'bar' => { 'baz' => 'bop' } } + expect(last_request.POST['foo']['bar']['baz']).to eq('bop') end - it "sends params with arrays" do - post "/", "photo" => uploaded_file, "foo" => ["1", "2"] - expect(last_request.POST["foo"]).to eq(["1", "2"]) + it 'sends params with arrays' do + post '/', 'photo' => uploaded_file, 'foo' => %w[1 2] + expect(last_request.POST['foo']).to eq(%w[1 2]) end - it "sends params with encoding sensitive values" do - post "/", "photo" => uploaded_file, "foo" => "bar? baz" - expect(last_request.POST["foo"]).to eq("bar? baz") + it 'sends params with encoding sensitive values' do + post '/', 'photo' => uploaded_file, 'foo' => 'bar? baz' + expect(last_request.POST['foo']).to eq('bar? baz') end - it "sends params encoded as ISO-8859-1" do - post "/", "photo" => uploaded_file, "foo" => "bar", "utf8" => "☃" - expect(last_request.POST["foo"]).to eq("bar") + it 'sends params encoded as ISO-8859-1' do + post '/', 'photo' => uploaded_file, 'foo' => 'bar', 'utf8' => '☃' + expect(last_request.POST['foo']).to eq('bar') - if Rack::Test.encoding_aware_strings? - expect(last_request.POST["utf8"]).to eq("☃") + expected_value = if Rack::Test.encoding_aware_strings? + '☃' else - expect(last_request.POST["utf8"]).to eq("\xE2\x98\x83") + "\xE2\x98\x83" end + + expect(last_request.POST['utf8']).to eq(expected_value) end - it "sends params with parens in names" do - post "/", "photo" => uploaded_file, "foo(1i)" => "bar" - expect(last_request.POST["foo(1i)"]).to eq("bar") + it 'sends params with parens in names' do + post '/', 'photo' => uploaded_file, 'foo(1i)' => 'bar' + expect(last_request.POST['foo(1i)']).to eq('bar') end - it "sends params with encoding sensitive names" do - post "/", "photo" => uploaded_file, "foo bar" => "baz" - expect(last_request.POST["foo bar"]).to eq("baz") + it 'sends params with encoding sensitive names' do + post '/', 'photo' => uploaded_file, 'foo bar' => 'baz' + expect(last_request.POST['foo bar']).to eq('baz') end - it "sends files with the filename" do - post "/", "photo" => uploaded_file - expect(last_request.POST["photo"][:filename]).to eq("foo.txt") + it 'sends files with the filename' do + post '/', 'photo' => uploaded_file + expect(last_request.POST['photo'][:filename]).to eq('foo.txt') end - it "sends files with the text/plain MIME type by default" do - post "/", "photo" => uploaded_file - expect(last_request.POST["photo"][:type]).to eq("text/plain") + it 'sends files with the text/plain MIME type by default' do + post '/', 'photo' => uploaded_file + expect(last_request.POST['photo'][:type]).to eq('text/plain') end - it "sends files with the right name" do - post "/", "photo" => uploaded_file - expect(last_request.POST["photo"][:name]).to eq("photo") + it 'sends files with the right name' do + post '/', 'photo' => uploaded_file + expect(last_request.POST['photo'][:name]).to eq('photo') end - it "allows overriding the content type" do - post "/", "photo" => Rack::Test::UploadedFile.new(test_file_path, "image/jpeg") - expect(last_request.POST["photo"][:type]).to eq("image/jpeg") + it 'allows overriding the content type' do + post '/', 'photo' => Rack::Test::UploadedFile.new(test_file_path, 'image/jpeg') + expect(last_request.POST['photo'][:type]).to eq('image/jpeg') end - it "sends files with a Content-Length in the header" do - post "/", "photo" => uploaded_file - expect(last_request.POST["photo"][:head]).to include("Content-Length: 4") + it 'sends files with a Content-Length in the header' do + post '/', 'photo' => uploaded_file + expect(last_request.POST['photo'][:head]).to include('Content-Length: 4') end - it "sends files as Tempfiles" do - post "/", "photo" => uploaded_file - expect(last_request.POST["photo"][:tempfile]).to be_a(::Tempfile) + it 'sends files as Tempfiles' do + post '/', 'photo' => uploaded_file + expect(last_request.POST['photo'][:tempfile]).to be_a(::Tempfile) end end - - context "uploading two files" do - it "sends the multipart/form-data content type" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - expect(last_request.env["CONTENT_TYPE"]).to include("multipart/form-data;") + context 'uploading two files' do + it 'sends the multipart/form-data content type' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + expect(last_request.env['CONTENT_TYPE']).to include('multipart/form-data;') end - it "sends files with the filename" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - expect(last_request.POST["photos"].collect{|photo| photo[:filename]}).to eq(["foo.txt", "bar.txt"]) + it 'sends files with the filename' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + expect(last_request.POST['photos'].collect { |photo| photo[:filename] }).to eq(['foo.txt', 'bar.txt']) end - it "sends files with the text/plain MIME type by default" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - expect(last_request.POST["photos"].collect{|photo| photo[:type]}).to eq(["text/plain", "text/plain"]) + it 'sends files with the text/plain MIME type by default' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + expect(last_request.POST['photos'].collect { |photo| photo[:type] }).to eq(['text/plain', 'text/plain']) end - it "sends files with the right names" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - last_request.POST["photos"].all?{|photo| expect(photo[:name]).to eq("photos[]") } + it 'sends files with the right names' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + last_request.POST['photos'].all? { |photo| expect(photo[:name]).to eq('photos[]') } end - it "allows mixed content types" do - image_file = Rack::Test::UploadedFile.new(test_file_path, "image/jpeg") + it 'allows mixed content types' do + image_file = Rack::Test::UploadedFile.new(test_file_path, 'image/jpeg') - post "/", "photos" => [uploaded_file, image_file] - expect(last_request.POST["photos"].collect{|photo| photo[:type]}).to eq(["text/plain", "image/jpeg"]) + post '/', 'photos' => [uploaded_file, image_file] + expect(last_request.POST['photos'].collect { |photo| photo[:type] }).to eq(['text/plain', 'image/jpeg']) end - it "sends files with a Content-Length in the header" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - last_request.POST["photos"].all?{|photo| expect(photo[:head]).to include("Content-Length: 4") } + it 'sends files with a Content-Length in the header' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + last_request.POST['photos'].all? { |photo| expect(photo[:head]).to include('Content-Length: 4') } end - it "sends both files as Tempfiles" do - post "/", "photos" => [uploaded_file, second_uploaded_file] - last_request.POST["photos"].all?{|photo| expect(photo[:tempfile]).to be_a(::Tempfile) } + it 'sends both files as Tempfiles' do + post '/', 'photos' => [uploaded_file, second_uploaded_file] + last_request.POST['photos'].all? { |photo| expect(photo[:tempfile]).to be_a(::Tempfile) } end end end diff --git a/spec/rack/test/uploaded_file_spec.rb b/spec/rack/test/uploaded_file_spec.rb index 634d491b..420fe9c2 100644 --- a/spec/rack/test/uploaded_file_spec.rb +++ b/spec/rack/test/uploaded_file_spec.rb @@ -1,17 +1,17 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::UploadedFile do def test_file_path - File.dirname(__FILE__) + "/../../fixtures/foo.txt" + File.dirname(__FILE__) + '/../../fixtures/foo.txt' end - it "returns an instance of `Rack::Test::UploadedFile`" do + it 'returns an instance of `Rack::Test::UploadedFile`' do uploaded_file = Rack::Test::UploadedFile.new(test_file_path) expect(uploaded_file).to be_a(Rack::Test::UploadedFile) end - it "responds to things that Tempfile responds to" do + it 'responds to things that Tempfile responds to' do uploaded_file = Rack::Test::UploadedFile.new(test_file_path) expect(uploaded_file).to respond_to(:close) @@ -30,29 +30,23 @@ def test_file_path it "creates Tempfiles with original file's extension" do uploaded_file = Rack::Test::UploadedFile.new(test_file_path) - expect(File.extname(uploaded_file.path)).to eq(".txt") + expect(File.extname(uploaded_file.path)).to eq('.txt') end - context "it should call its destructor" do - it "calls the destructor" do + context 'it should call its destructor' do + it 'calls the destructor' do expect(Rack::Test::UploadedFile).to receive(:actually_finalize).at_least(:once) if RUBY_PLATFORM == 'java' require 'java' java_import 'java.lang.System' - 50.times do |i| - uploaded_file = Rack::Test::UploadedFile.new(test_file_path) - - uploaded_file = nil - - System.gc() + 50.times do |_i| + Rack::Test::UploadedFile.new(test_file_path) + System.gc end else - uploaded_file = Rack::Test::UploadedFile.new(test_file_path) - - uploaded_file = nil - + Rack::Test::UploadedFile.new(test_file_path) GC.start end end diff --git a/spec/rack/test/utils_spec.rb b/spec/rack/test/utils_spec.rb index d94a249f..c00178fe 100644 --- a/spec/rack/test/utils_spec.rb +++ b/spec/rack/test/utils_spec.rb @@ -1,198 +1,198 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::Utils do include Rack::Test::Utils - describe "build_nested_query" do - it "converts empty strings to =" do - expect(build_nested_query("")).to eq("=") + describe 'build_nested_query' do + it 'converts empty strings to =' do + expect(build_nested_query('')).to eq('=') end - it "converts nil to an empty string" do - expect(build_nested_query(nil)).to eq("") + it 'converts nil to an empty string' do + expect(build_nested_query(nil)).to eq('') end - it "converts hashes with nil values" do - expect(build_nested_query(:a => nil)).to eq("a") + it 'converts hashes with nil values' do + expect(build_nested_query(a: nil)).to eq('a') end - it "converts hashes" do - expect(build_nested_query(:a => 1)).to eq("a=1") + it 'converts hashes' do + expect(build_nested_query(a: 1)).to eq('a=1') end - it "converts hashes with multiple keys" do - hash = { :a => 1, :b => 2 } - expect(["a=1&b=2", "b=2&a=1"]).to include(build_nested_query(hash)) + it 'converts hashes with multiple keys' do + hash = { a: 1, b: 2 } + expect(['a=1&b=2', 'b=2&a=1']).to include(build_nested_query(hash)) end - it "converts arrays with one element" do - expect(build_nested_query(:a => [1])).to eq("a[]=1") + it 'converts arrays with one element' do + expect(build_nested_query(a: [1])).to eq('a[]=1') end - it "converts arrays with multiple elements" do - expect(build_nested_query(:a => [1, 2])).to eq("a[]=1&a[]=2") + it 'converts arrays with multiple elements' do + expect(build_nested_query(a: [1, 2])).to eq('a[]=1&a[]=2') end it "converts arrays with brackets '[]' in the name" do - expect(build_nested_query("a[]" => [1, 2])).to eq("a%5B%5D=1&a%5B%5D=2") + expect(build_nested_query('a[]' => [1, 2])).to eq('a%5B%5D=1&a%5B%5D=2') end - it "converts nested hashes" do - expect(build_nested_query(:a => { :b => 1 })).to eq("a[b]=1") + it 'converts nested hashes' do + expect(build_nested_query(a: { b: 1 })).to eq('a[b]=1') end - it "converts arrays nested in a hash" do - expect(build_nested_query(:a => { :b => [1, 2] })).to eq("a[b][]=1&a[b][]=2") + it 'converts arrays nested in a hash' do + expect(build_nested_query(a: { b: [1, 2] })).to eq('a[b][]=1&a[b][]=2') end - it "converts arrays of hashes" do - expect(build_nested_query(:a => [{ :b => 2}, { :c => 3}])).to eq("a[][b]=2&a[][c]=3") + it 'converts arrays of hashes' do + expect(build_nested_query(a: [{ b: 2 }, { c: 3 }])).to eq('a[][b]=2&a[][c]=3') end - it "supports hash keys with empty arrays" do + it 'supports hash keys with empty arrays' do input = { collection: [] } expect(build_nested_query(input)).to eq('collection[]=') end end - describe "Rack::Test::Utils.build_multipart" do - it "builds multipart bodies" do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("submit-name" => "Larry", "files" => files) + describe 'Rack::Test::Utils.build_multipart' do + it 'builds multipart bodies' do + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('submit-name' => 'Larry', 'files' => files) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["submit-name"]).to eq("Larry") - check expect(params["files"][:filename]).to eq("foo.txt") - expect(params["files"][:tempfile].read).to eq("bar\n") + check expect(params['submit-name']).to eq('Larry') + check expect(params['files'][:filename]).to eq('foo.txt') + expect(params['files'][:tempfile].read).to eq("bar\n") end - it "builds multipart bodies from array of files" do - files = [Rack::Test::UploadedFile.new(multipart_file("foo.txt")), Rack::Test::UploadedFile.new(multipart_file("bar.txt"))] - data = Rack::Test::Utils.build_multipart("submit-name" => "Larry", "files" => files) + it 'builds multipart bodies from array of files' do + files = [Rack::Test::UploadedFile.new(multipart_file('foo.txt')), Rack::Test::UploadedFile.new(multipart_file('bar.txt'))] + data = Rack::Test::Utils.build_multipart('submit-name' => 'Larry', 'files' => files) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["submit-name"]).to eq("Larry") + check expect(params['submit-name']).to eq('Larry') - check expect(params["files"][0][:filename]).to eq("foo.txt") - expect(params["files"][0][:tempfile].read).to eq("bar\n") + check expect(params['files'][0][:filename]).to eq('foo.txt') + expect(params['files'][0][:tempfile].read).to eq("bar\n") - check expect(params["files"][1][:filename]).to eq("bar.txt") - expect(params["files"][1][:tempfile].read).to eq("baz\n") + check expect(params['files'][1][:filename]).to eq('bar.txt') + expect(params['files'][1][:tempfile].read).to eq("baz\n") end - it "builds nested multipart bodies" do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("people" => [{"submit-name" => "Larry", "files" => files}], "foo" => ['1', '2']) + it 'builds nested multipart bodies' do + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('people' => [{ 'submit-name' => 'Larry', 'files' => files }], 'foo' => %w[1 2]) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["people"][0]["submit-name"]).to eq("Larry") - check expect(params["people"][0]["files"][:filename]).to eq("foo.txt") - expect(params["people"][0]["files"][:tempfile].read).to eq("bar\n") - check expect(params["foo"]).to eq(["1", "2"]) + check expect(params['people'][0]['submit-name']).to eq('Larry') + check expect(params['people'][0]['files'][:filename]).to eq('foo.txt') + expect(params['people'][0]['files'][:tempfile].read).to eq("bar\n") + check expect(params['foo']).to eq(%w[1 2]) end - it "builds nested multipart bodies with an array of hashes" do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("files" => files, "foo" => [{"id" => "1", "name" => 'Dave'}, {"id" => "2", "name" => 'Steve'}]) + it 'builds nested multipart bodies with an array of hashes' do + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('files' => files, 'foo' => [{ 'id' => '1', 'name' => 'Dave' }, { 'id' => '2', 'name' => 'Steve' }]) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["files"][:filename]).to eq("foo.txt") - expect(params["files"][:tempfile].read).to eq("bar\n") - check expect(params["foo"]).to eq([{"id" => "1", "name" => "Dave"}, {"id" => "2", "name" => "Steve"}]) + check expect(params['files'][:filename]).to eq('foo.txt') + expect(params['files'][:tempfile].read).to eq("bar\n") + check expect(params['foo']).to eq([{ 'id' => '1', 'name' => 'Dave' }, { 'id' => '2', 'name' => 'Steve' }]) end - it "builds nested multipart bodies with arbitrarily nested array of hashes" do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("files" => files, "foo" => {"bar" => [{"id" => "1", "name" => 'Dave'}, - {"id" => "2", "name" => 'Steve', "qux" => [{"id" => '3', "name" => 'mike'}, - {"id" => '4', "name" => 'Joan'}]}]}) + it 'builds nested multipart bodies with arbitrarily nested array of hashes' do + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('files' => files, 'foo' => { 'bar' => [{ 'id' => '1', 'name' => 'Dave' }, + { 'id' => '2', 'name' => 'Steve', 'qux' => [{ 'id' => '3', 'name' => 'mike' }, + { 'id' => '4', 'name' => 'Joan' }] }] }) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["files"][:filename]).to eq("foo.txt") - expect(params["files"][:tempfile].read).to eq("bar\n") - check expect(params["foo"]).to eq({"bar" => [{"id" => "1", "name" => "Dave"}, - {"id" => "2", "name" => "Steve", "qux" => [{"id" => '3', "name" => 'mike'}, - {"id" => '4', "name" => 'Joan'}]}]}) + check expect(params['files'][:filename]).to eq('foo.txt') + expect(params['files'][:tempfile].read).to eq("bar\n") + check expect(params['foo']).to eq('bar' => [{ 'id' => '1', 'name' => 'Dave' }, + { 'id' => '2', 'name' => 'Steve', 'qux' => [{ 'id' => '3', 'name' => 'mike' }, + { 'id' => '4', 'name' => 'Joan' }] }]) end it 'does not break with params that look nested, but are not' do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("foo[]" => "1", "bar[]" => {"qux" => "2"}, "files[]" => files) + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('foo[]' => '1', 'bar[]' => { 'qux' => '2' }, 'files[]' => files) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["files"][0][:filename]).to eq("foo.txt") - expect(params["files"][0][:tempfile].read).to eq("bar\n") - check expect(params["foo"][0]).to eq("1") - check expect(params["bar"][0]).to eq({"qux" => "2"}) + check expect(params['files'][0][:filename]).to eq('foo.txt') + expect(params['files'][0][:tempfile].read).to eq("bar\n") + check expect(params['foo'][0]).to eq('1') + check expect(params['bar'][0]).to eq('qux' => '2') end it 'allows for nested files' do - files = Rack::Test::UploadedFile.new(multipart_file("foo.txt")) - data = Rack::Test::Utils.build_multipart("foo" => [{"id" => "1", "data" => files}, - {"id" => "2", "data" => ["3", "4"]}]) + files = Rack::Test::UploadedFile.new(multipart_file('foo.txt')) + data = Rack::Test::Utils.build_multipart('foo' => [{ 'id' => '1', 'data' => files }, + { 'id' => '2', 'data' => %w[3 4] }]) options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", - "CONTENT_LENGTH" => data.length.to_s, + 'CONTENT_TYPE' => "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}", + 'CONTENT_LENGTH' => data.length.to_s, :input => StringIO.new(data) } - env = Rack::MockRequest.env_for("/", options) + env = Rack::MockRequest.env_for('/', options) params = Rack::Multipart.parse_multipart(env) - check expect(params["foo"][0]["id"]).to eq("1") - check expect(params["foo"][0]["data"][:filename]).to eq("foo.txt") - expect(params["foo"][0]["data"][:tempfile].read).to eq("bar\n") - check expect(params["foo"][1]).to eq({"id" => "2", "data" => ["3", "4"]}) + check expect(params['foo'][0]['id']).to eq('1') + check expect(params['foo'][0]['data'][:filename]).to eq('foo.txt') + expect(params['foo'][0]['data'][:tempfile].read).to eq("bar\n") + check expect(params['foo'][1]).to eq('id' => '2', 'data' => %w[3 4]) end - it "returns nil if no UploadedFiles were used" do - data = Rack::Test::Utils.build_multipart("people" => [{"submit-name" => "Larry", "files" => "contents"}]) + it 'returns nil if no UploadedFiles were used' do + data = Rack::Test::Utils.build_multipart('people' => [{ 'submit-name' => 'Larry', 'files' => 'contents' }]) expect(data).to be_nil end - it "raises ArgumentErrors if params is not a Hash" do - expect { - Rack::Test::Utils.build_multipart("foo=bar") - }.to raise_error(ArgumentError, "value must be a Hash") + it 'raises ArgumentErrors if params is not a Hash' do + expect do + Rack::Test::Utils.build_multipart('foo=bar') + end.to raise_error(ArgumentError, 'value must be a Hash') end def multipart_file(name) - File.join(File.dirname(__FILE__), "..", "..", "fixtures", name.to_s) + File.join(File.dirname(__FILE__), '..', '..', 'fixtures', name.to_s) end end end diff --git a/spec/rack/test_spec.rb b/spec/rack/test_spec.rb index 1fc871ed..a9828a03 100644 --- a/spec/rack/test_spec.rb +++ b/spec/rack/test_spec.rb @@ -1,153 +1,153 @@ -require "spec_helper" +require 'spec_helper' describe Rack::Test::Session do - describe "initialization" do - it "supports being initialized with a Rack::MockSession app" do + describe 'initialization' do + it 'supports being initialized with a Rack::MockSession app' do session = Rack::Test::Session.new(Rack::MockSession.new(app)) - expect(session.request("/")).to be_ok + expect(session.request('/')).to be_ok end - it "supports being initialized with an app" do + it 'supports being initialized with an app' do session = Rack::Test::Session.new(app) - expect(session.request("/")).to be_ok + expect(session.request('/')).to be_ok end end - describe "#request" do - it "requests the URI using GET by default" do - request "/" + describe '#request' do + it 'requests the URI using GET by default' do + request '/' expect(last_request).to be_get expect(last_response).to be_ok end - it "returns a response" do - expect(request("/")).to be_ok + it 'returns a response' do + expect(request('/')).to be_ok end - it "uses the provided env" do - request "/", "X-Foo" => "bar" - expect(last_request.env["X-Foo"]).to eq("bar") + it 'uses the provided env' do + request '/', 'X-Foo' => 'bar' + expect(last_request.env['X-Foo']).to eq('bar') end - it "allows HTTP_HOST to be set" do - request "/", "HTTP_HOST" => "www.example.ua" - expect(last_request.env['HTTP_HOST']).to eq("www.example.ua") + it 'allows HTTP_HOST to be set' do + request '/', 'HTTP_HOST' => 'www.example.ua' + expect(last_request.env['HTTP_HOST']).to eq('www.example.ua') end - it "sets HTTP_HOST with port for non-default ports" do - request "http://foo.com:8080" - expect(last_request.env["HTTP_HOST"]).to eq("foo.com:8080") - request "https://foo.com:8443" - expect(last_request.env["HTTP_HOST"]).to eq("foo.com:8443") + it 'sets HTTP_HOST with port for non-default ports' do + request 'http://foo.com:8080' + expect(last_request.env['HTTP_HOST']).to eq('foo.com:8080') + request 'https://foo.com:8443' + expect(last_request.env['HTTP_HOST']).to eq('foo.com:8443') end - it "sets HTTP_HOST without port for default ports" do - request "http://foo.com" - expect(last_request.env["HTTP_HOST"]).to eq("foo.com") - request "http://foo.com:80" - expect(last_request.env["HTTP_HOST"]).to eq("foo.com") - request "https://foo.com:443" - expect(last_request.env["HTTP_HOST"]).to eq("foo.com") + it 'sets HTTP_HOST without port for default ports' do + request 'http://foo.com' + expect(last_request.env['HTTP_HOST']).to eq('foo.com') + request 'http://foo.com:80' + expect(last_request.env['HTTP_HOST']).to eq('foo.com') + request 'https://foo.com:443' + expect(last_request.env['HTTP_HOST']).to eq('foo.com') end - it "defaults to GET" do - request "/" - expect(last_request.env["REQUEST_METHOD"]).to eq("GET") + it 'defaults to GET' do + request '/' + expect(last_request.env['REQUEST_METHOD']).to eq('GET') end - it "defaults the REMOTE_ADDR to 127.0.0.1" do - request "/" - expect(last_request.env["REMOTE_ADDR"]).to eq("127.0.0.1") + it 'defaults the REMOTE_ADDR to 127.0.0.1' do + request '/' + expect(last_request.env['REMOTE_ADDR']).to eq('127.0.0.1') end - it "sets rack.test to true in the env" do - request "/" - expect(last_request.env["rack.test"]).to eq(true) + it 'sets rack.test to true in the env' do + request '/' + expect(last_request.env['rack.test']).to eq(true) end - it "defaults to port 80" do - request "/" - expect(last_request.env["SERVER_PORT"]).to eq("80") + it 'defaults to port 80' do + request '/' + expect(last_request.env['SERVER_PORT']).to eq('80') end - it "defaults to example.org" do - request "/" - expect(last_request.env["SERVER_NAME"]).to eq("example.org") + it 'defaults to example.org' do + request '/' + expect(last_request.env['SERVER_NAME']).to eq('example.org') end - it "yields the response to a given block" do - request "/" do |response| + it 'yields the response to a given block' do + request '/' do |response| expect(response).to be_ok end end - it "supports sending :params" do - request "/", :params => { "foo" => "bar" } - expect(last_request.GET["foo"]).to eq("bar") + it 'supports sending :params' do + request '/', params: { 'foo' => 'bar' } + expect(last_request.GET['foo']).to eq('bar') end it "doesn't follow redirects by default" do - request "/redirect" + request '/redirect' expect(last_response).to be_redirect expect(last_response.body).to be_empty end - it "allows passing :input in for POSTs" do - request "/", :method => :post, :input => "foo" - expect(last_request.env["rack.input"].read).to eq("foo") + it 'allows passing :input in for POSTs' do + request '/', method: :post, input: 'foo' + expect(last_request.env['rack.input'].read).to eq('foo') end - it "converts method names to a uppercase strings" do - request "/", :method => :put - expect(last_request.env["REQUEST_METHOD"]).to eq("PUT") + it 'converts method names to a uppercase strings' do + request '/', method: :put + expect(last_request.env['REQUEST_METHOD']).to eq('PUT') end - it "prepends a slash to the URI path" do - request "foo" - expect(last_request.env["PATH_INFO"]).to eq("/foo") + it 'prepends a slash to the URI path' do + request 'foo' + expect(last_request.env['PATH_INFO']).to eq('/foo') end - it "accepts params and builds query strings for GET requests" do - request "/foo?baz=2", :params => {:foo => {:bar => "1"}} - expect(last_request.GET).to eq({ "baz" => "2", "foo" => { "bar" => "1" }}) + it 'accepts params and builds query strings for GET requests' do + request '/foo?baz=2', params: { foo: { bar: '1' } } + expect(last_request.GET).to eq('baz' => '2', 'foo' => { 'bar' => '1' }) end - it "parses query strings with repeated variable names correctly" do - request "/foo?bar=2&bar=3" - expect(last_request.GET).to eq({ "bar" => "3" }) + it 'parses query strings with repeated variable names correctly' do + request '/foo?bar=2&bar=3' + expect(last_request.GET).to eq('bar' => '3') end - it "accepts raw input in params for GET requests" do - request "/foo?baz=2", :params => "foo[bar]=1" - expect(last_request.GET).to eq({ "baz" => "2", "foo" => { "bar" => "1" }}) + it 'accepts raw input in params for GET requests' do + request '/foo?baz=2', params: 'foo[bar]=1' + expect(last_request.GET).to eq('baz' => '2', 'foo' => { 'bar' => '1' }) end - it "does not rewrite a GET query string when :params is not supplied" do - request "/foo?a=1&b=2&c=3&e=4&d=5+%20" - expect(last_request.query_string).to eq("a=1&b=2&c=3&e=4&d=5+%20") + it 'does not rewrite a GET query string when :params is not supplied' do + request '/foo?a=1&b=2&c=3&e=4&d=5+%20' + expect(last_request.query_string).to eq('a=1&b=2&c=3&e=4&d=5+%20') end - it "does not rewrite a GET query string when :params is empty" do - request "/foo?a=1&b=2&c=3&e=4&d=5", :params => {} - last_request.query_string.should == "a=1&b=2&c=3&e=4&d=5" + it 'does not rewrite a GET query string when :params is empty' do + request '/foo?a=1&b=2&c=3&e=4&d=5', params: {} + last_request.query_string.should == 'a=1&b=2&c=3&e=4&d=5' end - it "does not overwrite multiple query string keys" do - request "/foo?a=1&a=2", :params => { :bar => 1 } - expect(last_request.query_string).to eq("a=1&a=2&bar=1") + it 'does not overwrite multiple query string keys' do + request '/foo?a=1&a=2', params: { bar: 1 } + expect(last_request.query_string).to eq('a=1&a=2&bar=1') end - it "accepts params and builds url encoded params for POST requests" do - request "/foo", :method => :post, :params => {:foo => {:bar => "1"}} - expect(last_request.env["rack.input"].read).to eq("foo[bar]=1") + it 'accepts params and builds url encoded params for POST requests' do + request '/foo', method: :post, params: { foo: { bar: '1' } } + expect(last_request.env['rack.input'].read).to eq('foo[bar]=1') end - it "accepts raw input in params for POST requests" do - request "/foo", :method => :post, :params => "foo[bar]=1" - expect(last_request.env["rack.input"].read).to eq("foo[bar]=1") + it 'accepts raw input in params for POST requests' do + request '/foo', method: :post, params: 'foo[bar]=1' + expect(last_request.env['rack.input'].read).to eq('foo[bar]=1') end - context "when the response body responds_to?(:close)" do + context 'when the response body responds_to?(:close)' do class CloseableBody def initialize @closed = false @@ -155,7 +155,7 @@ def initialize def each return if @closed - yield "Hello, World!" + yield 'Hello, World!' end def close @@ -167,276 +167,276 @@ def close body = CloseableBody.new expect(body).to receive(:close) - app = lambda do |env| - [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, body] + app = lambda do |_env| + [200, { 'Content-Type' => 'text/html', 'Content-Length' => '13' }, body] end session = Rack::Test::Session.new(Rack::MockSession.new(app)) - session.request("/") + session.request('/') end it "closes response's body after iteration" do - app = lambda do |env| - [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, CloseableBody.new] + app = lambda do |_env| + [200, { 'Content-Type' => 'text/html', 'Content-Length' => '13' }, CloseableBody.new] end session = Rack::Test::Session.new(Rack::MockSession.new(app)) - session.request("/") - expect(session.last_response.body).to eq("Hello, World!") + session.request('/') + expect(session.last_response.body).to eq('Hello, World!') end end - context "when input is given" do - it "sends the input" do - request "/", :method => "POST", :input => "foo" - expect(last_request.env["rack.input"].read).to eq("foo") + context 'when input is given' do + it 'sends the input' do + request '/', method: 'POST', input: 'foo' + expect(last_request.env['rack.input'].read).to eq('foo') end - it "does not send a multipart request" do - request "/", :method => "POST", :input => "foo" - expect(last_request.env["CONTENT_TYPE"]).not_to eq("application/x-www-form-urlencoded") + it 'does not send a multipart request' do + request '/', method: 'POST', input: 'foo' + expect(last_request.env['CONTENT_TYPE']).not_to eq('application/x-www-form-urlencoded') end end - context "for a POST specified with :method" do - it "uses application/x-www-form-urlencoded as the CONTENT_TYPE" do - request "/", :method => "POST" - expect(last_request.env["CONTENT_TYPE"]).to eq("application/x-www-form-urlencoded") + context 'for a POST specified with :method' do + it 'uses application/x-www-form-urlencoded as the CONTENT_TYPE' do + request '/', method: 'POST' + expect(last_request.env['CONTENT_TYPE']).to eq('application/x-www-form-urlencoded') end end - context "for a POST specified with REQUEST_METHOD" do - it "uses application/x-www-form-urlencoded as the CONTENT_TYPE" do - request "/", "REQUEST_METHOD" => "POST" - expect(last_request.env["CONTENT_TYPE"]).to eq("application/x-www-form-urlencoded") + context 'for a POST specified with REQUEST_METHOD' do + it 'uses application/x-www-form-urlencoded as the CONTENT_TYPE' do + request '/', 'REQUEST_METHOD' => 'POST' + expect(last_request.env['CONTENT_TYPE']).to eq('application/x-www-form-urlencoded') end end - context "when CONTENT_TYPE is specified in the env" do - it "does not overwrite the CONTENT_TYPE" do - request "/", "CONTENT_TYPE" => "application/xml" - expect(last_request.env["CONTENT_TYPE"]).to eq("application/xml") + context 'when CONTENT_TYPE is specified in the env' do + it 'does not overwrite the CONTENT_TYPE' do + request '/', 'CONTENT_TYPE' => 'application/xml' + expect(last_request.env['CONTENT_TYPE']).to eq('application/xml') end end - context "when the URL is https://" do - it "sets rack.url_scheme to https" do - get "https://example.org/" - expect(last_request.env["rack.url_scheme"]).to eq("https") + context 'when the URL is https://' do + it 'sets rack.url_scheme to https' do + get 'https://example.org/' + expect(last_request.env['rack.url_scheme']).to eq('https') end - it "sets SERVER_PORT to 443" do - get "https://example.org/" - expect(last_request.env["SERVER_PORT"]).to eq("443") + it 'sets SERVER_PORT to 443' do + get 'https://example.org/' + expect(last_request.env['SERVER_PORT']).to eq('443') end - it "sets HTTPS to on" do - get "https://example.org/" - expect(last_request.env["HTTPS"]).to eq("on") + it 'sets HTTPS to on' do + get 'https://example.org/' + expect(last_request.env['HTTPS']).to eq('on') end end - context "for a XHR" do - it "sends XMLHttpRequest for the X-Requested-With header" do - request "/", :xhr => true - expect(last_request.env["HTTP_X_REQUESTED_WITH"]).to eq("XMLHttpRequest") + context 'for a XHR' do + it 'sends XMLHttpRequest for the X-Requested-With header' do + request '/', xhr: true + expect(last_request.env['HTTP_X_REQUESTED_WITH']).to eq('XMLHttpRequest') expect(last_request).to be_xhr end end end - describe "#header" do - it "sets a header to be sent with requests" do - header "User-Agent", "Firefox" - request "/" + describe '#header' do + it 'sets a header to be sent with requests' do + header 'User-Agent', 'Firefox' + request '/' - expect(last_request.env["HTTP_USER_AGENT"]).to eq("Firefox") + expect(last_request.env['HTTP_USER_AGENT']).to eq('Firefox') end - it "sets a Content-Type to be sent with requests" do - header "Content-Type", "application/json" - request "/" + it 'sets a Content-Type to be sent with requests' do + header 'Content-Type', 'application/json' + request '/' - expect(last_request.env["CONTENT_TYPE"]).to eq("application/json") + expect(last_request.env['CONTENT_TYPE']).to eq('application/json') end - it "sets a Host to be sent with requests" do - header "Host", "www.example.ua" - request "/" + it 'sets a Host to be sent with requests' do + header 'Host', 'www.example.ua' + request '/' - expect(last_request.env["HTTP_HOST"]).to eq("www.example.ua") + expect(last_request.env['HTTP_HOST']).to eq('www.example.ua') end - it "persists across multiple requests" do - header "User-Agent", "Firefox" - request "/" - request "/" + it 'persists across multiple requests' do + header 'User-Agent', 'Firefox' + request '/' + request '/' - expect(last_request.env["HTTP_USER_AGENT"]).to eq("Firefox") + expect(last_request.env['HTTP_USER_AGENT']).to eq('Firefox') end - it "overwrites previously set headers" do - header "User-Agent", "Firefox" - header "User-Agent", "Safari" - request "/" + it 'overwrites previously set headers' do + header 'User-Agent', 'Firefox' + header 'User-Agent', 'Safari' + request '/' - expect(last_request.env["HTTP_USER_AGENT"]).to eq("Safari") + expect(last_request.env['HTTP_USER_AGENT']).to eq('Safari') end - it "can be used to clear a header" do - header "User-Agent", "Firefox" - header "User-Agent", nil - request "/" + it 'can be used to clear a header' do + header 'User-Agent', 'Firefox' + header 'User-Agent', nil + request '/' - expect(last_request.env).not_to have_key("HTTP_USER_AGENT") + expect(last_request.env).not_to have_key('HTTP_USER_AGENT') end - it "is overridden by headers sent during the request" do - header "User-Agent", "Firefox" - request "/", "HTTP_USER_AGENT" => "Safari" + it 'is overridden by headers sent during the request' do + header 'User-Agent', 'Firefox' + request '/', 'HTTP_USER_AGENT' => 'Safari' - expect(last_request.env["HTTP_USER_AGENT"]).to eq("Safari") + expect(last_request.env['HTTP_USER_AGENT']).to eq('Safari') end end - describe "#env" do - it "sets the env to be sent with requests" do - env "rack.session", {:csrf => 'token'} - request "/" + describe '#env' do + it 'sets the env to be sent with requests' do + env 'rack.session', csrf: 'token' + request '/' - expect(last_request.env["rack.session"]).to eq({:csrf => 'token'}) + expect(last_request.env['rack.session']).to eq(csrf: 'token') end - it "persists across multiple requests" do - env "rack.session", {:csrf => 'token'} - request "/" - request "/" + it 'persists across multiple requests' do + env 'rack.session', csrf: 'token' + request '/' + request '/' - expect(last_request.env["rack.session"]).to eq({:csrf => 'token'}) + expect(last_request.env['rack.session']).to eq(csrf: 'token') end - it "overwrites previously set envs" do - env "rack.session", {:csrf => 'token'} - env "rack.session", {:some => :thing} - request "/" + it 'overwrites previously set envs' do + env 'rack.session', csrf: 'token' + env 'rack.session', some: :thing + request '/' - expect(last_request.env["rack.session"]).to eq({:some => :thing}) + expect(last_request.env['rack.session']).to eq(some: :thing) end - it "can be used to clear a env" do - env "rack.session", {:csrf => 'token'} - env "rack.session", nil - request "/" + it 'can be used to clear a env' do + env 'rack.session', csrf: 'token' + env 'rack.session', nil + request '/' - expect(last_request.env).not_to have_key("X_CSRF_TOKEN") + expect(last_request.env).not_to have_key('X_CSRF_TOKEN') end - it "is overridden by envs sent during the request" do - env "rack.session", {:csrf => 'token'} - request "/", "rack.session" => {:some => :thing} + it 'is overridden by envs sent during the request' do + env 'rack.session', csrf: 'token' + request '/', 'rack.session' => { some: :thing } - expect(last_request.env["rack.session"]).to eq({:some => :thing}) + expect(last_request.env['rack.session']).to eq(some: :thing) end end - describe "#basic_authorize" do - it "sets the HTTP_AUTHORIZATION header" do - authorize "bryan", "secret" - request "/" + describe '#basic_authorize' do + it 'sets the HTTP_AUTHORIZATION header' do + authorize 'bryan', 'secret' + request '/' - expect(last_request.env["HTTP_AUTHORIZATION"]).to eq("Basic YnJ5YW46c2VjcmV0") + expect(last_request.env['HTTP_AUTHORIZATION']).to eq('Basic YnJ5YW46c2VjcmV0') end - it "includes the header for subsequent requests" do - basic_authorize "bryan", "secret" - request "/" - request "/" + it 'includes the header for subsequent requests' do + basic_authorize 'bryan', 'secret' + request '/' + request '/' - expect(last_request.env["HTTP_AUTHORIZATION"]).to eq("Basic YnJ5YW46c2VjcmV0") + expect(last_request.env['HTTP_AUTHORIZATION']).to eq('Basic YnJ5YW46c2VjcmV0') end end - describe "follow_redirect!" do - it "follows redirects" do - get "/redirect" + describe 'follow_redirect!' do + it 'follows redirects' do + get '/redirect' follow_redirect! expect(last_response).not_to be_redirect expect(last_response.body).to eq("You've been redirected") - expect(last_request.env["HTTP_REFERER"]).to eql("http://example.org/redirect") + expect(last_request.env['HTTP_REFERER']).to eql('http://example.org/redirect') end - it "does not include params when following the redirect" do - get "/redirect", { "foo" => "bar" } + it 'does not include params when following the redirect' do + get '/redirect', 'foo' => 'bar' follow_redirect! expect(last_request.GET).to eq({}) end - it "raises an error if the last_response is not set" do - expect { + it 'raises an error if the last_response is not set' do + expect do follow_redirect! - }.to raise_error(Rack::Test::Error) + end.to raise_error(Rack::Test::Error) end - it "raises an error if the last_response is not a redirect" do - get "/" + it 'raises an error if the last_response is not a redirect' do + get '/' - expect { + expect do follow_redirect! - }.to raise_error(Rack::Test::Error) + end.to raise_error(Rack::Test::Error) end - context "for HTTP 307" do - it "keeps the original method" do - post "/redirect?status=307", {foo: "bar"} + context 'for HTTP 307' do + it 'keeps the original method' do + post '/redirect?status=307', foo: 'bar' follow_redirect! - last_response.body.should include "post" - last_response.body.should include "foo" - last_response.body.should include "bar" + last_response.body.should include 'post' + last_response.body.should include 'foo' + last_response.body.should include 'bar' end end end - describe "#last_request" do - it "returns the most recent request" do - request "/" - expect(last_request.env["PATH_INFO"]).to eq("/") + describe '#last_request' do + it 'returns the most recent request' do + request '/' + expect(last_request.env['PATH_INFO']).to eq('/') end - it "raises an error if no requests have been issued" do - expect { + it 'raises an error if no requests have been issued' do + expect do last_request - }.to raise_error(Rack::Test::Error) + end.to raise_error(Rack::Test::Error) end end - describe "#last_response" do - it "returns the most recent response" do - request "/" - expect(last_response["Content-Type"]).to eq("text/html;charset=utf-8") + describe '#last_response' do + it 'returns the most recent response' do + request '/' + expect(last_response['Content-Type']).to eq('text/html;charset=utf-8') end - it "raises an error if no requests have been issued",focus: true do - expect { + it 'raises an error if no requests have been issued', focus: true do + expect do last_response - }.to raise_error(Rack::Test::Error) + end.to raise_error(Rack::Test::Error) end end - describe "after_request" do - it "runs callbacks after each request" do + describe 'after_request' do + it 'runs callbacks after each request' do ran = false rack_mock_session.after_request do ran = true end - get "/" + get '/' expect(ran).to eq(true) end - it "runs multiple callbacks" do + it 'runs multiple callbacks' do count = 0 2.times do @@ -445,132 +445,132 @@ def close end end - get "/" + get '/' expect(count).to eq(2) end end - describe "#get" do - it_should_behave_like "any #verb methods" + describe '#get' do + it_should_behave_like 'any #verb methods' def verb - "get" + 'get' end - it "uses the provided params hash" do - get "/", :foo => "bar" - expect(last_request.GET).to eq({ "foo" => "bar" }) + it 'uses the provided params hash' do + get '/', foo: 'bar' + expect(last_request.GET).to eq('foo' => 'bar') end - it "sends params with parens in names" do - get "/", "foo(1i)" => "bar" - expect(last_request.GET["foo(1i)"]).to eq("bar") + it 'sends params with parens in names' do + get '/', 'foo(1i)' => 'bar' + expect(last_request.GET['foo(1i)']).to eq('bar') end - it "supports params with encoding sensitive names" do - get "/", "foo bar" => "baz" - expect(last_request.GET["foo bar"]).to eq("baz") + it 'supports params with encoding sensitive names' do + get '/', 'foo bar' => 'baz' + expect(last_request.GET['foo bar']).to eq('baz') end - it "supports params with nested encoding sensitive names" do - get "/", "boo" => {"foo bar" => "baz"} - expect(last_request.GET).to eq({"boo" => {"foo bar" => "baz"}}) + it 'supports params with nested encoding sensitive names' do + get '/', 'boo' => { 'foo bar' => 'baz' } + expect(last_request.GET).to eq('boo' => { 'foo bar' => 'baz' }) end - it "accepts params in the path" do - get "/?foo=bar" - expect(last_request.GET).to eq({ "foo" => "bar" }) + it 'accepts params in the path' do + get '/?foo=bar' + expect(last_request.GET).to eq('foo' => 'bar') end end - describe "#head" do - it_should_behave_like "any #verb methods" + describe '#head' do + it_should_behave_like 'any #verb methods' def verb - "head" + 'head' end end - describe "#post" do - it_should_behave_like "any #verb methods" + describe '#post' do + it_should_behave_like 'any #verb methods' def verb - "post" + 'post' end - it "uses the provided params hash" do - post "/", :foo => "bar" - expect(last_request.POST).to eq({ "foo" => "bar" }) + it 'uses the provided params hash' do + post '/', foo: 'bar' + expect(last_request.POST).to eq('foo' => 'bar') end - it "supports params with encoding sensitive names" do - post "/", "foo bar" => "baz" - expect(last_request.POST["foo bar"]).to eq("baz") + it 'supports params with encoding sensitive names' do + post '/', 'foo bar' => 'baz' + expect(last_request.POST['foo bar']).to eq('baz') end - it "uses application/x-www-form-urlencoded as the default CONTENT_TYPE" do - post "/" - expect(last_request.env["CONTENT_TYPE"]).to eq("application/x-www-form-urlencoded") + it 'uses application/x-www-form-urlencoded as the default CONTENT_TYPE' do + post '/' + expect(last_request.env['CONTENT_TYPE']).to eq('application/x-www-form-urlencoded') end - it "accepts a body" do - post "/", "Lobsterlicious!" - expect(last_request.body.read).to eq("Lobsterlicious!") + it 'accepts a body' do + post '/', 'Lobsterlicious!' + expect(last_request.body.read).to eq('Lobsterlicious!') end - context "when CONTENT_TYPE is specified in the env" do - it "does not overwrite the CONTENT_TYPE" do - post "/", {}, { "CONTENT_TYPE" => "application/xml" } - expect(last_request.env["CONTENT_TYPE"]).to eq("application/xml") + context 'when CONTENT_TYPE is specified in the env' do + it 'does not overwrite the CONTENT_TYPE' do + post '/', {}, 'CONTENT_TYPE' => 'application/xml' + expect(last_request.env['CONTENT_TYPE']).to eq('application/xml') end end end - describe "#put" do - it_should_behave_like "any #verb methods" + describe '#put' do + it_should_behave_like 'any #verb methods' def verb - "put" + 'put' end - it "accepts a body" do - put "/", "Lobsterlicious!" - expect(last_request.body.read).to eq("Lobsterlicious!") + it 'accepts a body' do + put '/', 'Lobsterlicious!' + expect(last_request.body.read).to eq('Lobsterlicious!') end end - describe "#patch" do - it_should_behave_like "any #verb methods" + describe '#patch' do + it_should_behave_like 'any #verb methods' def verb - "patch" + 'patch' end - it "accepts a body" do - patch "/", "Lobsterlicious!" - expect(last_request.body.read).to eq("Lobsterlicious!") + it 'accepts a body' do + patch '/', 'Lobsterlicious!' + expect(last_request.body.read).to eq('Lobsterlicious!') end end - describe "#delete" do - it_should_behave_like "any #verb methods" + describe '#delete' do + it_should_behave_like 'any #verb methods' def verb - "delete" + 'delete' end - it "does not set a content type" do - delete "/" + it 'does not set a content type' do + delete '/' - expect(last_request.env['CONTENT_TYPE']).to be_nil - end + expect(last_request.env['CONTENT_TYPE']).to be_nil + end end - describe "#options" do - it_should_behave_like "any #verb methods" + describe '#options' do + it_should_behave_like 'any #verb methods' def verb - "options" + 'options' end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index de84ddf1..90bb92e1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,16 +1,16 @@ -require "rubygems" -require "bundler/setup" +require 'rubygems' +require 'bundler/setup' -require "codeclimate-test-reporter" +require 'codeclimate-test-reporter' CodeClimate::TestReporter.start -require "rack" -require "rspec" +require 'rack' +require 'rspec' -Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} +Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |f| require f } -require "rack/test" -require File.dirname(__FILE__) + "/fixtures/fake_app" +require 'rack/test' +require File.dirname(__FILE__) + '/fixtures/fake_app' RSpec.configure do |config| config.mock_with :rspec @@ -20,28 +20,26 @@ def app Rack::Lint.new(Rack::Test::FakeApp.new) end - def check(*args) - end - + def check(*args); end end -shared_examples_for "any #verb methods" do - it "requests the URL using VERB" do - send(verb, "/") +shared_examples_for 'any #verb methods' do + it 'requests the URL using VERB' do + send(verb, '/') - check expect(last_request.env["REQUEST_METHOD"]).to eq(verb.upcase) + check expect(last_request.env['REQUEST_METHOD']).to eq(verb.upcase) expect(last_response).to be_ok end - it "uses the provided env" do - send(verb, "/", {}, { "HTTP_USER_AGENT" => "Rack::Test" }) - expect(last_request.env["HTTP_USER_AGENT"]).to eq("Rack::Test") + it 'uses the provided env' do + send(verb, '/', {}, 'HTTP_USER_AGENT' => 'Rack::Test') + expect(last_request.env['HTTP_USER_AGENT']).to eq('Rack::Test') end - it "yields the response to a given block" do + it 'yields the response to a given block' do yielded = false - send(verb, "/") do |response| + send(verb, '/') do |response| expect(response).to be_ok yielded = true end @@ -49,20 +47,20 @@ def check(*args) expect(yielded).to be_truthy end - it "sets the HTTP_HOST header with port" do - send(verb, "http://example.org:8080/uri") - expect(last_request.env["HTTP_HOST"]).to eq("example.org:8080") + it 'sets the HTTP_HOST header with port' do + send(verb, 'http://example.org:8080/uri') + expect(last_request.env['HTTP_HOST']).to eq('example.org:8080') end - it "sets the HTTP_HOST header without port" do - send(verb, "/uri") - expect(last_request.env["HTTP_HOST"]).to eq("example.org") + it 'sets the HTTP_HOST header without port' do + send(verb, '/uri') + expect(last_request.env['HTTP_HOST']).to eq('example.org') end - context "for a XHR" do - it "sends XMLHttpRequest for the X-Requested-With header" do - send(verb, "/", {}, { :xhr => true }) - expect(last_request.env["HTTP_X_REQUESTED_WITH"]).to eq("XMLHttpRequest") + context 'for a XHR' do + it 'sends XMLHttpRequest for the X-Requested-With header' do + send(verb, '/', {}, xhr: true) + expect(last_request.env['HTTP_X_REQUESTED_WITH']).to eq('XMLHttpRequest') expect(last_request).to be_xhr end end diff --git a/spec/support/matchers/challenge.rb b/spec/support/matchers/challenge.rb index 08ab9b1d..4d29aae5 100644 --- a/spec/support/matchers/challenge.rb +++ b/spec/support/matchers/challenge.rb @@ -1,11 +1,11 @@ RSpec::Matchers.define :be_challenge do match do |actual_response| actual_response.status == 401 && - actual_response['WWW-Authenticate'] =~ /^Digest / && - actual_response.body.empty? + actual_response['WWW-Authenticate'] =~ /^Digest / && + actual_response.body.empty? end description do - "a HTTP Digest challenge response" + 'a HTTP Digest challenge response' end end