aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack')
-rw-r--r--actionpack/CHANGELOG.md433
-rw-r--r--actionpack/MIT-LICENSE2
-rw-r--r--actionpack/actionpack.gemspec6
-rw-r--r--actionpack/lib/abstract_controller/base.rb37
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb53
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb14
-rw-r--r--actionpack/lib/abstract_controller/railties/routes_helpers.rb4
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb15
-rw-r--r--actionpack/lib/abstract_controller/translation.rb15
-rw-r--r--actionpack/lib/action_controller.rb2
-rw-r--r--actionpack/lib/action_controller/base.rb3
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb10
-rw-r--r--actionpack/lib/action_controller/metal.rb17
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb82
-rw-r--r--actionpack/lib/action_controller/metal/etag_with_template_digest.rb4
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb2
-rw-r--r--actionpack/lib/action_controller/metal/head.rb6
-rw-r--r--actionpack/lib/action_controller/metal/hide_actions.rb40
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb27
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb13
-rw-r--r--actionpack/lib/action_controller/metal/live.rb8
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb45
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb7
-rw-r--r--actionpack/lib/action_controller/metal/rack_delegation.rb12
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb3
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb11
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb32
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb23
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb2
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb6
-rw-r--r--actionpack/lib/action_controller/model_naming.rb12
-rw-r--r--actionpack/lib/action_controller/renderer.rb100
-rw-r--r--actionpack/lib/action_controller/test_case.rb142
-rw-r--r--actionpack/lib/action_dispatch.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb7
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb3
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/parameter_filter.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb8
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb23
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb13
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb113
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/gtg/transition_table.rb6
-rw-r--r--actionpack/lib/action_dispatch/journey/nfa/transition_table.rb47
-rw-r--r--actionpack/lib/action_dispatch/journey/path/pattern.rb9
-rw-r--r--actionpack/lib/action_dispatch/journey/route.rb8
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb5
-rw-r--r--actionpack/lib/action_dispatch/journey/scanner.rb10
-rw-r--r--actionpack/lib/action_dispatch/journey/visualizer/fsm.css4
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb24
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb80
-rw-r--r--actionpack/lib/action_dispatch/middleware/exception_wrapper.rb72
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb39
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/request_id.rb12
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb11
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb16
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb40
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/request/utils.rb4
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb6
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb49
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb15
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb103
-rw-r--r--actionpack/lib/action_dispatch/routing/routes_proxy.rb9
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb6
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/dom.rb3
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb3
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/tag.rb3
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb302
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/test_response.rb7
-rw-r--r--actionpack/lib/action_pack.rb2
-rw-r--r--actionpack/lib/action_pack/gem_version.rb6
-rw-r--r--actionpack/test/abstract/callbacks_test.rb8
-rw-r--r--actionpack/test/abstract/translation_test.rb33
-rw-r--r--actionpack/test/abstract_unit.rb6
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb11
-rw-r--r--actionpack/test/controller/base_test.rb66
-rw-r--r--actionpack/test/controller/caching_test.rb8
-rw-r--r--actionpack/test/controller/default_url_options_with_before_action_test.rb3
-rw-r--r--actionpack/test/controller/filters_test.rb62
-rw-r--r--actionpack/test/controller/flash_hash_test.rb34
-rw-r--r--actionpack/test/controller/flash_test.rb16
-rw-r--r--actionpack/test/controller/force_ssl_test.rb6
-rw-r--r--actionpack/test/controller/helper_test.rb28
-rw-r--r--actionpack/test/controller/http_basic_authentication_test.rb7
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb23
-rw-r--r--actionpack/test/controller/integration_test.rb426
-rw-r--r--actionpack/test/controller/localized_templates_test.rb6
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb32
-rw-r--r--actionpack/test/controller/mime/accept_format_test.rb4
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb52
-rw-r--r--actionpack/test/controller/mime/responders_test.rb32
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb9
-rw-r--r--actionpack/test/controller/new_base/content_negotiation_test.rb4
-rw-r--r--actionpack/test/controller/new_base/content_type_test.rb4
-rw-r--r--actionpack/test/controller/new_base/render_action_test.rb4
-rw-r--r--actionpack/test/controller/new_base/render_layout_test.rb6
-rw-r--r--actionpack/test/controller/new_base/render_streaming_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb4
-rw-r--r--actionpack/test/controller/new_base/render_test.rb6
-rw-r--r--actionpack/test/controller/parameters/parameters_permit_test.rb6
-rw-r--r--actionpack/test/controller/params_wrapper_test.rb48
-rw-r--r--actionpack/test/controller/permitted_params_test.rb4
-rw-r--r--actionpack/test/controller/render_js_test.rb4
-rw-r--r--actionpack/test/controller/render_json_test.rb4
-rw-r--r--actionpack/test/controller/render_test.rb182
-rw-r--r--actionpack/test/controller/render_xml_test.rb4
-rw-r--r--actionpack/test/controller/renderer_test.rb103
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb99
-rw-r--r--actionpack/test/controller/required_params_test.rb8
-rw-r--r--actionpack/test/controller/resources_test.rb8
-rw-r--r--actionpack/test/controller/routing_test.rb14
-rw-r--r--actionpack/test/controller/send_file_test.rb1
-rw-r--r--actionpack/test/controller/show_exceptions_test.rb12
-rw-r--r--actionpack/test/controller/test_case_test.rb455
-rw-r--r--actionpack/test/controller/url_for_integration_test.rb1
-rw-r--r--actionpack/test/controller/url_for_test.rb26
-rw-r--r--actionpack/test/controller/webservice_test.rb31
-rw-r--r--actionpack/test/dispatch/cookies_test.rb32
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb148
-rw-r--r--actionpack/test/dispatch/exception_wrapper_test.rb114
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb4
-rw-r--r--actionpack/test/dispatch/mount_test.rb2
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb12
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb15
-rw-r--r--actionpack/test/dispatch/request/query_string_parsing_test.rb9
-rw-r--r--actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb4
-rw-r--r--actionpack/test/dispatch/request_id_test.rb2
-rw-r--r--actionpack/test/dispatch/request_test.rb27
-rw-r--r--actionpack/test/dispatch/response_test.rb22
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb44
-rw-r--r--actionpack/test/dispatch/routing/route_set_test.rb48
-rw-r--r--actionpack/test/dispatch/routing_test.rb136
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb10
-rw-r--r--actionpack/test/dispatch/session/mem_cache_store_test.rb2
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb24
-rw-r--r--actionpack/test/dispatch/ssl_test.rb2
-rw-r--r--actionpack/test/dispatch/static_test.rb24
-rw-r--r--actionpack/test/dispatch/template_assertions_test.rb14
-rw-r--r--actionpack/test/dispatch/test_request_test.rb2
-rw-r--r--actionpack/test/dispatch/url_generation_test.rb4
-rw-r--r--actionpack/test/fixtures/helpers_typo/admin/users_helper.rb5
-rw-r--r--actionpack/test/fixtures/localized/hello_world.de.html2
-rw-r--r--actionpack/test/journey/path/pattern_test.rb2
-rw-r--r--actionpack/test/journey/route/definition/scanner_test.rb25
-rw-r--r--actionpack/test/journey/router/utils_test.rb1
-rw-r--r--actionpack/test/journey/router_test.rb12
-rw-r--r--actionpack/test/routing/helper_test.rb14
157 files changed, 3269 insertions, 1695 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index de9722c392..055d4b4f5b 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,376 +1,233 @@
-* Deprecate implicit Array conversion for Response objects. It was added
- (using `#to_ary`) so we could conveniently use implicit splatting:
+* Non-string authenticity tokens do not raise NoMethodError when decoding
+ the masked token.
- status, headers, body = response
+ *Ville Lautanala*
- But it also means `response + response` works and `[response].flatten`
- cascades down to the Rack body. Nonsense behavior. Instead, rely on
- explicit conversion and splatting with `#to_a`:
+* Add http_cache_forever to Action Controller, so we can cache a response that never gets expired.
- status, header, body = *response
+ *arthurnn*
- *Jeremy Kemper*
+* ActionController#translate supports symbols as shortcuts.
+ When shortcut is given it also lookups without action name.
-* Don't rescue `IPAddr::InvalidAddressError`.
+ *Max Melentiev*
- `IPAddr::InvalidAddressError` does not exist in Ruby 1.9.3
- and fails for JRuby in 1.9 mode.
+* Expand `ActionController::ConditionalGet#fresh_when` and `stale?` to also
+ accept a collection of records as the first argument, so that the
+ following code can be written in a shorter form.
- *Peter Suschlik*
+ # Before
+ def index
+ @articles = Article.all
+ fresh_when(etag: @articles, last_modified: @articles.maximum(:updated_at))
+ end
-* Fix bug where the router would ignore any constraints added to redirect
- routes.
+ # After
+ def index
+ @articles = Article.all
+ fresh_when(@articles)
+ end
- Fixes #16605.
+ *claudiob*
- *Agis Anastasopoulos*
+* Explicitly ignored wildcard verbs when searching for HEAD routes before fallback
-* Allow `config.action_dispatch.trusted_proxies` to accept an IPAddr object.
+ Fixes an issue where a mounted rack app at root would intercept the HEAD
+ request causing an incorrect behavior during the fall back to GET requests.
Example:
+ ```ruby
+ draw do
+ get '/home' => 'test#index'
+ mount rack_app, at: '/'
+ end
+ head '/home'
+ assert_response :success
+ ```
+ In this case, a HEAD request runs through the routes the first time and fails
+ to match anything. Then, it runs through the list with the fallback and matches
+ `get '/home'`. The original behavior would match the rack app in the first pass.
- # config/environments/production.rb
- config.action_dispatch.trusted_proxies = IPAddr.new('4.8.15.0/16')
+ *Terence Sun*
- *Sam Aarons*
+* Migrating xhr methods to keyword arguments syntax
+ in `ActionController::TestCase` and `ActionDispatch::Integration`
-* Avoid duplicating routes for HEAD requests.
+ Old syntax:
- Instead of duplicating the routes, we will first match the HEAD request to
- HEAD routes. If no match is found, we will then map the HEAD request to
- GET routes.
+ xhr :get, :create, params: { id: 1 }
- *Guo Xiang Tan*, *Andrew White*
+ New syntax example:
-* Requests that hit `ActionDispatch::Static` can now take advantage
- of gzipped assets on disk. By default a gzip asset will be served if
- the client supports gzip and a compressed file is on disk.
+ get :create, params: { id: 1 }, xhr: true
- *Richard Schneeman*
+ *Kir Shatrov*
-* `ActionController::Parameters` will stop inheriting from `Hash` and
- `HashWithIndifferentAccess` in the next major release. If you use any method
- that is not available on `ActionController::Parameters` you should consider
- calling `#to_h` to convert it to a `Hash` first before calling that method.
+* Migrating to keyword arguments syntax in `ActionController::TestCase` and
+ `ActionDispatch::Integration` HTTP request methods.
- *Prem Sichanugrist*
-
-* `ActionController::Parameters#to_h` now returns a `Hash` with unpermitted
- keys removed. This change is to reflect on a security concern where some
- method performed on an `ActionController::Parameters` may yield a `Hash`
- object which does not maintain `permitted?` status. If you would like to
- get a `Hash` with all the keys intact, duplicate and mark it as permitted
- before calling `#to_h`.
-
- params = ActionController::Parameters.new({
- name: 'Senjougahara Hitagi',
- oddity: 'Heavy stone crab'
- })
- params.to_h
- # => {}
-
- unsafe_params = params.dup.permit!
- unsafe_params.to_h
- # => {"name"=>"Senjougahara Hitagi", "oddity"=>"Heavy stone crab"}
-
- safe_params = params.permit(:name)
- safe_params.to_h
- # => {"name"=>"Senjougahara Hitagi"}
-
- This change is consider a stopgap as we cannot change the code to stop
- `ActionController::Parameters` to inherit from `HashWithIndifferentAccess`
- in the next minor release.
-
- *Prem Sichanugrist*
-
-* Deprecated `TagAssertions`.
-
- *Kasper Timm Hansen*
-
-* Use the Active Support JSON encoder for cookie jars using the `:json` or
- `:hybrid` serializer. This allows you to serialize custom Ruby objects into
- cookies by defining the `#as_json` hook on such objects.
-
- Fixes #16520.
-
- *Godfrey Chan*
-
-* Add `config.action_dispatch.cookies_digest` option for setting custom
- digest. The default remains the same - 'SHA1'.
-
- *Łukasz Strzałkowski*
-
-* Move `respond_with` (and the class-level `respond_to`) to
- the `responders` gem.
-
- *José Valim*
-
-* When your templates change, browser caches bust automatically.
-
- New default: the template digest is automatically included in your ETags.
- When you call `fresh_when @post`, the digest for `posts/show.html.erb`
- is mixed in so future changes to the HTML will blow HTTP caches for you.
- This makes it easy to HTTP-cache many more of your actions.
-
- If you render a different template, you can now pass the `:template`
- option to include its digest instead:
-
- fresh_when @post, template: 'widgets/show'
-
- Pass `template: false` to skip the lookup. To turn this off entirely, set:
-
- config.action_controller.etag_with_template_digest = false
-
- *Jeremy Kemper*
-
-* Remove deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError`
- in favor of `AbstractController::Helpers::MissingHelperError`.
-
- *Yves Senn*
-
-* Fix `assert_template` not being able to assert that no files were rendered.
-
- *Guo Xiang Tan*
-
-* Extract source code for the entire exception stack trace for
- better debugging and diagnosis.
-
- *Ryan Dao*
-
-* Allows ActionDispatch::Request::LOCALHOST to match any IPv4 127.0.0.0/8
- loopback address.
-
- *Earl St Sauver*, *Sven Riedel*
-
-* Preserve original path in `ShowExceptions` middleware by stashing it as
- `env["action_dispatch.original_path"]`
-
- `ActionDispatch::ShowExceptions` overwrites `PATH_INFO` with the status code
- for the exception defined in `ExceptionWrapper`, so the path
- the user was visiting when an exception occurred was not previously
- available to any custom exceptions_app. The original `PATH_INFO` is now
- stashed in `env["action_dispatch.original_path"]`.
-
- *Grey Baker*
-
-* Use `String#bytesize` instead of `String#size` when checking for cookie
- overflow.
-
- *Agis Anastasopoulos*
-
-* `render nothing: true` or rendering a `nil` body no longer add a single
- space to the response body.
-
- The old behavior was added as a workaround for a bug in an early version of
- Safari, where the HTTP headers are not returned correctly if the response
- body has a 0-length. This is been fixed since and the workaround is no
- longer necessary.
-
- Use `render body: ' '` if the old behavior is desired.
-
- See #14883 for details.
-
- *Godfrey Chan*
-
-* Prepend a JS comment to JSONP callbacks. Addresses CVE-2014-4671
- ("Rosetta Flash").
-
- *Greg Campbell*
-
-* Because URI paths may contain non US-ASCII characters we need to force
- the encoding of any unescaped URIs to UTF-8 if they are US-ASCII.
- This essentially replicates the functionality of the monkey patch to
- URI.parser.unescape in active_support/core_ext/uri.rb.
-
- Fixes #16104.
-
- *Karl Entwistle*
-
-* Generate shallow paths for all children of shallow resources.
-
- Fixes #15783.
-
- *Seb Jacobs*
-
-* JSONP responses are now rendered with the `text/javascript` content type
- when rendering through a `respond_to` block.
-
- Fixes #15081.
-
- *Lucas Mazza*
-
-* Add `config.action_controller.always_permitted_parameters` to configure which
- parameters are permitted globally. The default value of this configuration is
- `['controller', 'action']`.
-
- *Gary S. Weaver*, *Rafael Chacon*
-
-* Fix env['PATH_INFO'] missing leading slash when a rack app mounted at '/'.
-
- Fixes #15511.
-
- *Larry Lv*
+ Example:
-* ActionController::Parameters#require now accepts `false` values.
+ post :create, params: { y: x }, session: { a: 'b' }
+ get :view, params: { id: 1 }
+ get :view, params: { id: 1 }, format: :json
- Fixes #15685.
+ *Kir Shatrov*
- *Sergio Romano*
+* Preserve default url options when generating URLs.
-* With authorization header `Authorization: Token token=`, `authenticate` now
- recognize token as nil, instead of "token".
+ Fixes an issue that would cause default_url_options to be lost when
+ generating URLs with fewer positional arguments than parameters in the
+ route definition.
- Fixes #14846.
+ *Tekin Suleyman*
- *Larry Lv*
+* Deprecate *_via_redirect integration test methods.
-* Ensure the controller is always notified as soon as the client disconnects
- during live streaming, even when the controller is blocked on a write.
+ Use `follow_redirect!` manually after the request call for the same behavior.
- *Nicholas Jakobsen*, *Matthew Draper*
+ *Aditya Kapoor*
-* Routes specifying 'to:' must be a string that contains a "#" or a rack
- application. Use of a symbol should be replaced with `action: symbol`.
- Use of a string without a "#" should be replaced with `controller: string`.
+* Add `ActionController::Renderer` to render arbitrary templates
+ outside controller actions.
- *Aaron Patterson*
+ Its functionality is accessible through class methods `render` and
+ `renderer` of `ActionController::Base`.
-* Fix URL generation with `:trailing_slash` such that it does not add
- a trailing slash after `.:format`
+ *Ravil Bayramgalin*
- *Dan Langevin*
+* Support `:assigns` option when rendering with controllers/mailers.
-* Build full URI as string when processing path in integration tests for
- performance reasons.
+ *Ravil Bayramgalin*
- *Guo Xiang Tan*
+* Default headers, removed in controller actions, are no longer reapplied on
+ the test response.
-* Fix `'Stack level too deep'` when rendering `head :ok` in an action method
- called 'status' in a controller.
+ *Jonas Baumann*
- Fixes #13905.
+* Deprecate all *_filter callbacks in favor of *_action callbacks.
- *Christiaan Van den Poel*
+ *Rafael Mendonça França*
-* Add MKCALENDAR HTTP method (RFC 4791).
+* Allow you to pass `prepend: false` to protect_from_forgery to have the
+ verification callback appended instead of prepended to the chain.
+ This allows you to let the verification step depend on prior callbacks.
- *Sergey Karpesh*
+ Example:
-* Instrument fragment cache metrics.
+ class ApplicationController < ActionController::Base
+ before_action :authenticate
+ protect_from_forgery prepend: false, unless: -> { @authenticated_by.oauth? }
- Adds `:controller`: and `:action` keys to the instrumentation payload
- for the `*_fragment.action_controller` notifications. This allows tracking
- e.g. the fragment cache hit rates for each controller action.
+ private
+ def authenticate
+ if oauth_request?
+ # authenticate with oauth
+ @authenticated_by = 'oauth'.inquiry
+ else
+ # authenticate with cookies
+ @authenticated_by = 'cookie'.inquiry
+ end
+ end
+ end
- *Daniel Schierbeck*
+ *Josef Šimánek*
-* Always use the provided port if the protocol is relative.
+* Remove `ActionController::HideActions`.
- Fixes #15043.
+ *Ravil Bayramgalin*
- *Guilherme Cavalcanti*, *Andrew White*
+* Remove `respond_to`/`respond_with` placeholder methods, this functionality
+ has been extracted to the `responders` gem.
-* Moved `params[request_forgery_protection_token]` into its own method
- and improved tests.
+ *Carlos Antonio da Silva*
- Fixes #11316.
+* Remove deprecated assertion files.
- *Tom Kadwill*
+ *Rafael Mendonça França*
-* Added verification of route constraints given as a Proc or an object responding
- to `:matches?`. Previously, when given an non-complying object, it would just
- silently fail to enforce the constraint. It will now raise an `ArgumentError`
- when setting up the routes.
+* Remove deprecated usage of string keys in URL helpers.
- *Xavier Defrang*
+ *Rafael Mendonça França*
-* Properly treat the entire IPv6 User Local Address space as private for
- purposes of remote IP detection. Also handle uppercase private IPv6
- addresses.
+* Remove deprecated `only_path` option on `*_path` helpers.
- Fixes #12638.
+ *Rafael Mendonça França*
- *Caleb Spare*
+* Remove deprecated `NamedRouteCollection#helpers`.
-* Fixed an issue with migrating legacy json cookies.
+ *Rafael Mendonça França*
- Previously, the `VerifyAndUpgradeLegacySignedMessage` assumes all incoming
- cookies are marshal-encoded. This is not the case when `secret_token` is
- used in conjunction with the `:json` or `:hybrid` serializer.
+* Remove deprecated support to define routes with `:to` option that doesn't contain `#`.
- In those case, when upgrading to use `secret_key_base`, this would cause a
- `TypeError: incompatible marshal file format` and a 500 error for the user.
+ *Rafael Mendonça França*
- Fixes #14774.
+* Remove deprecated `ActionDispatch::Response#to_ary`.
- *Godfrey Chan*
+ *Rafael Mendonça França*
-* Make URL escaping more consistent:
+* Remove deprecated `ActionDispatch::Request#deep_munge`.
- 1. Escape '%' characters in URLs - only unescaped data should be passed to URL helpers
- 2. Add an `escape_segment` helper to `Router::Utils` that escapes '/' characters
- 3. Use `escape_segment` rather than `escape_fragment` in optimized URL generation
- 4. Use `escape_segment` rather than `escape_path` in URL generation
+ *Rafael Mendonça França*
- For point 4 there are two exceptions. Firstly, when a route uses wildcard segments
- (e.g. `*foo`) then we use `escape_path` as the value may contain '/' characters. This
- means that wildcard routes can't be optimized. Secondly, if a `:controller` segment
- is used in the path then this uses `escape_path` as the controller may be namespaced.
+* Remove deprecated `ActionDispatch::Http::Parameters#symbolized_path_parameters`.
- Fixes #14629, #14636 and #14070.
+ *Rafael Mendonça França*
- *Andrew White*, *Edho Arief*
+* Remove deprecated option `use_route` in controller tests.
-* Add alias `ActionDispatch::Http::UploadedFile#to_io` to
- `ActionDispatch::Http::UploadedFile#tempfile`.
+ *Rafael Mendonça França*
- *Tim Linquist*
+* Ensure `append_info_to_payload` is called even if an exception is raised.
-* Returns null type format when format is not know and controller is using `any`
- format block.
+ Fixes an issue where when an exception is raised in the request the additonal
+ payload data is not available.
- Fixes #14462.
+ See:
+ * #14903
+ * https://github.com/roidrage/lograge/issues/37
- *Rafael Mendonça França*
+ *Dieter Komendera*, *Margus Pärt*
-* Improve routing error page with fuzzy matching search.
+* Correctly rely on the response's status code to handle calls to `head`.
- *Winston*
+ *Robin Dupret*
-* Only make deeply nested routes shallow when parent is shallow.
+* Using `head` method returns empty response_body instead
+ of returning a single space " ".
- Fixes #14684.
+ The old behavior was added as a workaround for a bug in an early
+ version of Safari, where the HTTP headers are not returned correctly
+ if the response body has a 0-length. This is been fixed since and
+ the workaround is no longer necessary.
- *Andrew White*, *James Coglan*
+ Fixes #18253.
-* Append link to bad code to backtrace when exception is `SyntaxError`.
+ *Prathamesh Sonpatki*
- *Boris Kuznetsov*
+* Fix how polymorphic routes works with objects that implement `to_model`.
-* Swapped the parameters of assert_equal in `assert_select` so that the
- proper values were printed correctly.
+ *Travis Grathwell*
- Fixes #14422.
+* Stop converting empty arrays in `params` to `nil`.
- *Vishal Lal*
+ This behaviour was introduced in response to CVE-2012-2660, CVE-2012-2694
+ and CVE-2013-0155
-* The method `shallow?` returns false if the parent resource is a singleton so
- we need to check if we're not inside a nested scope before copying the :path
- and :as options to their shallow equivalents.
+ ActiveRecord now issues a safe query when passing an empty array into
+ a where clause, so there is no longer a need to defend against this type
+ of input (any nils are still stripped from the array).
- Fixes #14388.
+ *Chris Sinjakli*
- *Andrew White*
+* Fixed usage of optional scopes in url helpers.
-* Make logging of CSRF failures optional (but on by default) with the
- `log_warning_on_csrf_failure` configuration setting in
- `ActionController::RequestForgeryProtection`.
+ *Alex Robbin*
- *John Barton*
+* Fixed handling of positional url helper arguments when `format: false`.
-* Fix URL generation in controller tests with request-dependent
- `default_url_options` methods.
+ Fixes #17819.
- *Tony Wooster*
+ *Andrew White*, *Tatiana Soukiassian*
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionpack/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionpack/CHANGELOG.md) for previous changes.
diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE
index d58dd9ed9b..3ec7a617cf 100644
--- a/actionpack/MIT-LICENSE
+++ b/actionpack/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2014 David Heinemeier Hansson
+Copyright (c) 2004-2015 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 69a160fdc8..d9b23ad4a9 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.2.0'
s.license = 'MIT'
@@ -21,10 +21,10 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
- s.add_dependency 'rack', '~> 1.6.0.beta'
+ s.add_dependency 'rack', '~> 1.6'
s.add_dependency 'rack-test', '~> 0.6.2'
s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1'
- s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.3'
+ s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
s.add_dependency 'actionview', version
s.add_development_dependency 'activemodel', version
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index 4026dab2ce..c95b9a4097 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -12,7 +12,7 @@ module AbstractController
class ActionNotFound < StandardError
end
- # <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
+ # AbstractController::Base is a low-level API. Nobody should be
# using it directly, and subclasses (like ActionController::Base) are
# expected to provide their own +render+ method, since rendering means
# different things depending on the context.
@@ -57,21 +57,11 @@ module AbstractController
controller.public_instance_methods(true)
end
- # The list of hidden actions. Defaults to an empty array.
- # This can be modified by other modules or subclasses
- # to specify particular actions as hidden.
- #
- # ==== Returns
- # * <tt>Array</tt> - An array of method names that should not be considered actions.
- def hidden_actions
- []
- end
-
# A list of method names that should be considered actions. This
# includes all public instance methods on a controller, less
- # any internal methods (see #internal_methods), adding back in
+ # any internal methods (see internal_methods), adding back in
# any methods that are internal, but still exist on the class
- # itself. Finally, #hidden_actions are removed.
+ # itself.
#
# ==== Returns
# * <tt>Set</tt> - A set of all methods that should be considered actions.
@@ -82,25 +72,26 @@ module AbstractController
# Except for public instance methods of Base and its ancestors
internal_methods +
# Be sure to include shadowed public instance methods of this class
- public_instance_methods(false)).uniq.map { |x| x.to_s } -
- # And always exclude explicitly hidden actions
- hidden_actions.to_a
+ public_instance_methods(false)).uniq.map(&:to_s)
- # Clear out AS callback method pollution
- Set.new(methods.reject { |method| method =~ /_one_time_conditions/ })
+ methods.to_set
end
end
# action_methods are cached and there is sometimes need to refresh
- # them. clear_action_methods! allows you to do that, so next time
+ # them. ::clear_action_methods! allows you to do that, so next time
# you run action_methods, they will be recalculated
def clear_action_methods!
@action_methods = nil
end
# Returns the full controller name, underscored, without the ending Controller.
- # For instance, MyApp::MyPostsController would return "my_app/my_posts" for
- # controller_path.
+ #
+ # class MyApp::MyPostsController < AbstractController::Base
+ # end
+ # end
+ #
+ # MyApp::MyPostsController.controller_path # => "my_app/my_posts"
#
# ==== Returns
# * <tt>String</tt>
@@ -137,12 +128,12 @@ module AbstractController
process_action(action_name, *args)
end
- # Delegates to the class' #controller_path
+ # Delegates to the class' ::controller_path
def controller_path
self.class.controller_path
end
- # Delegates to the class' #action_methods
+ # Delegates to the class' ::action_methods
def action_methods
self.class.action_methods
end
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index ca5c80cd71..69f490b327 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -1,3 +1,5 @@
+require 'active_support/deprecation'
+
module AbstractController
module Callbacks
extend ActiveSupport::Concern
@@ -9,7 +11,7 @@ module AbstractController
included do
define_callbacks :process_action,
- terminator: ->(controller,_) { controller.response_body },
+ terminator: ->(controller, result_lambda) { result_lambda.call if result_lambda.is_a?(Proc); controller.response_body },
skip_after_callbacks_if_terminated: true
end
@@ -22,10 +24,21 @@ module AbstractController
end
module ClassMethods
- # If :only or :except are used, convert the options into the
- # :unless and :if options of ActiveSupport::Callbacks.
- # The basic idea is that :only => :index gets converted to
- # :if => proc {|c| c.action_name == "index" }.
+ # If +:only+ or +:except+ are used, convert the options into the
+ # +:if+ and +:unless+ options of ActiveSupport::Callbacks.
+ #
+ # The basic idea is that <tt>:only => :index</tt> gets converted to
+ # <tt>:if => proc {|c| c.action_name == "index" }</tt>.
+ #
+ # Note that <tt>:only</tt> has priority over <tt>:if</tt> in case they
+ # are used together.
+ #
+ # only: :index, if: -> { true } # the :if option will be ignored.
+ #
+ # Note that <tt>:if</tt> has priority over <tt>:except</tt> in case they
+ # are used together.
+ #
+ # except: :index, if: -> { true } # the :except option will be ignored.
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
@@ -54,7 +67,11 @@ module AbstractController
skip_after_action(*names)
skip_around_action(*names)
end
- alias_method :skip_filter, :skip_action_callback
+
+ def skip_filter(*names)
+ ActiveSupport::Deprecation.warn("#{callback}_filter is deprecated and will be removed in Rails 5.1. Use #{callback}_action instead.")
+ skip_action_callback(*names)
+ end
# Take callback names and an optional callback proc, normalize them,
# then call the block with each callback. This allows us to abstract
@@ -169,14 +186,22 @@ module AbstractController
set_callback(:process_action, callback, name, options)
end
end
- alias_method :"#{callback}_filter", :"#{callback}_action"
+
+ define_method "#{callback}_filter" do |*names, &blk|
+ ActiveSupport::Deprecation.warn("#{callback}_filter is deprecated and will be removed in Rails 5.1. Use #{callback}_action instead.")
+ send("#{callback}_action", *names, &blk)
+ end
define_method "prepend_#{callback}_action" do |*names, &blk|
_insert_callbacks(names, blk) do |name, options|
set_callback(:process_action, callback, name, options.merge(:prepend => true))
end
end
- alias_method :"prepend_#{callback}_filter", :"prepend_#{callback}_action"
+
+ define_method "prepend_#{callback}_filter" do |*names, &blk|
+ ActiveSupport::Deprecation.warn("prepend_#{callback}_filter is deprecated and will be removed in Rails 5.1. Use prepend_#{callback}_action instead.")
+ send("prepend_#{callback}_action", *names, &blk)
+ end
# Skip a before, after or around callback. See _insert_callbacks
# for details on the allowed parameters.
@@ -185,11 +210,19 @@ module AbstractController
skip_callback(:process_action, callback, name, options)
end
end
- alias_method :"skip_#{callback}_filter", :"skip_#{callback}_action"
+
+ define_method "skip_#{callback}_filter" do |*names, &blk|
+ ActiveSupport::Deprecation.warn("skip_#{callback}_filter is deprecated and will be removed in Rails 5.1. Use skip_#{callback}_action instead.")
+ send("skip_#{callback}_action", *names, &blk)
+ end
# *_action is the same as append_*_action
alias_method :"append_#{callback}_action", :"#{callback}_action"
- alias_method :"append_#{callback}_filter", :"#{callback}_action"
+
+ define_method "append_#{callback}_filter" do |*names, &blk|
+ ActiveSupport::Deprecation.warn("append_#{callback}_filter is deprecated and will be removed in Rails 5.1. Use append_#{callback}_action instead.")
+ send("append_#{callback}_action", *names, &blk)
+ end
end
end
end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 95c67d482b..109eff10eb 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -150,7 +150,17 @@ module AbstractController
rescue LoadError => e
raise AbstractController::Helpers::MissingHelperError.new(e, file_name)
end
- file_name.camelize.constantize
+
+ mod_name = file_name.camelize
+ begin
+ mod_name.constantize
+ rescue LoadError
+ # dependencies.rb gives a similar error message but its wording is
+ # not as clear because it mentions autoloading. To the user all it
+ # matters is that a helper module couldn't be loaded, autoloading
+ # is an internal mechanism that should not leak.
+ raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb"
+ end
when Module
arg
else
@@ -174,7 +184,7 @@ module AbstractController
module_name = name.sub(/Controller$/, '')
module_path = module_name.underscore
helper module_path
- rescue MissingSourceFile => e
+ rescue LoadError => e
raise e unless e.is_missing? "helpers/#{module_path}_helper"
rescue NameError => e
raise e unless e.missing_name? "#{module_name}Helper"
diff --git a/actionpack/lib/abstract_controller/railties/routes_helpers.rb b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
index 568c47e43a..14b574e322 100644
--- a/actionpack/lib/abstract_controller/railties/routes_helpers.rb
+++ b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
@@ -6,9 +6,9 @@ module AbstractController
define_method(:inherited) do |klass|
super(klass)
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
- klass.send(:include, namespace.railtie_routes_url_helpers(include_path_helpers))
+ klass.include(namespace.railtie_routes_url_helpers(include_path_helpers))
else
- klass.send(:include, routes.url_helpers(include_path_helpers))
+ klass.include(routes.url_helpers(include_path_helpers))
end
end
end
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index 9d10140ed2..5514213ad8 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -17,8 +17,8 @@ module AbstractController
extend ActiveSupport::Concern
include ActionView::ViewPaths
- # Normalize arguments, options and then delegates render_to_body and
- # sticks the result in self.response_body.
+ # Normalizes arguments, options and then delegates render_to_body and
+ # sticks the result in <tt>self.response_body</tt>.
# :api: public
def render(*args, &block)
options = _normalize_render(*args, &block)
@@ -30,11 +30,11 @@ module AbstractController
# Raw rendering of a template to a string.
#
# It is similar to render, except that it does not
- # set the response_body and it should be guaranteed
+ # set the +response_body+ and it should be guaranteed
# to always return a string.
#
- # If a component extends the semantics of response_body
- # (as Action Controller extends it to be anything that
+ # If a component extends the semantics of +response_body+
+ # (as ActionController extends it to be anything that
# responds to the method each), this method needs to be
# overridden in order to still return a string.
# :api: plugin
@@ -73,8 +73,9 @@ module AbstractController
}
end
- # Normalize args by converting render "foo" to render :action => "foo" and
- # render "foo/bar" to render :file => "foo/bar".
+ # Normalize args by converting <tt>render "foo"</tt> to
+ # <tt>render :action => "foo"</tt> and <tt>render "foo/bar"</tt> to
+ # <tt>render :file => "foo/bar"</tt>.
# :api: plugin
def _normalize_args(action=nil, options={})
if action.is_a? Hash
diff --git a/actionpack/lib/abstract_controller/translation.rb b/actionpack/lib/abstract_controller/translation.rb
index 02028d8e05..56b8ce895e 100644
--- a/actionpack/lib/abstract_controller/translation.rb
+++ b/actionpack/lib/abstract_controller/translation.rb
@@ -8,14 +8,15 @@ module AbstractController
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
# to translate many keys within the same controller / action and gives you a
# simple framework for scoping them consistently.
- def translate(*args)
- key = args.first
- if key.is_a?(String) && (key[0] == '.')
- key = "#{ controller_path.tr('/', '.') }.#{ action_name }#{ key }"
- args[0] = key
+ def translate(key, options = {})
+ if key.to_s.first == '.'
+ path = controller_path.tr('/', '.')
+ defaults = [:"#{path}#{key}"]
+ defaults << options[:default] if options[:default]
+ options[:default] = defaults
+ key = "#{path}.#{action_name}#{key}"
end
-
- I18n.translate(*args)
+ I18n.translate(key, options)
end
alias :t :translate
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 91ac7eef01..7667e469d3 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -11,6 +11,7 @@ module ActionController
autoload :Caching
autoload :Metal
autoload :Middleware
+ autoload :Renderer
autoload_under "metal" do
autoload :Compatibility
@@ -22,7 +23,6 @@ module ActionController
autoload :ForceSSL
autoload :Head
autoload :Helpers
- autoload :HideActions
autoload :HttpAuthentication
autoload :ImplicitRender
autoload :Instrumentation
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 7bbf938987..e6038396f9 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -44,7 +44,7 @@ module ActionController
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
#
# def server_ip
- # location = request.env["SERVER_ADDR"]
+ # location = request.env["REMOTE_ADDR"]
# render plain: "This server hosted at #{location}"
# end
#
@@ -206,7 +206,6 @@ module ActionController
AbstractController::AssetPaths,
Helpers,
- HideActions,
UrlFor,
Redirecting,
ActionView::Layouts,
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 89fa75f025..87609d8aa7 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -1,4 +1,3 @@
-
module ActionController
class LogSubscriber < ActiveSupport::LogSubscriber
INTERNAL_PARAMS = %w(controller action format _method only_path)
@@ -54,15 +53,6 @@ module ActionController
end
end
- def deep_munge(event)
- debug do
- "Value for params[:#{event.payload[:keys].join('][:')}] was set "\
- "to nil, because it was one of [], [null] or [null, null, ...]. "\
- "Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation "\
- "for more information."\
- end
- end
-
%w(write_fragment read_fragment exist_fragment?
expire_fragment expire_page write_page).each do |method|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index bfbc15a901..ae111e4951 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -165,7 +165,7 @@ module ActionController
headers["Location"] = url
end
- # basic url_for that can be overridden for more robust functionality
+ # Basic url_for that can be overridden for more robust functionality
def url_for(string)
string
end
@@ -173,6 +173,7 @@ module ActionController
def status
@_status
end
+ alias :response_code :status # :nodoc:
def status=(status)
@_status = Rack::Utils.status_code(status)
@@ -182,18 +183,22 @@ module ActionController
body = [body] unless body.nil? || body.respond_to?(:each)
super
end
-
+
# Tests if render or redirect has already happened.
def performed?
response_body || (response && response.committed?)
end
def dispatch(name, request) #:nodoc:
+ set_request!(request)
+ process(name)
+ to_a
+ end
+
+ def set_request!(request) #:nodoc:
@_request = request
@_env = request.env
@_env['action_controller.instance'] = self
- process(name)
- to_a
end
def to_a #:nodoc:
@@ -236,9 +241,5 @@ module ActionController
lambda { |env| new.dispatch(name, klass.new(env)) }
end
end
-
- def _status_code
- @_status
- end
end
end
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index b210ee3423..858870d8b8 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -51,21 +51,31 @@ module ActionController
#
# def show
# @article = Article.find(params[:id])
- # fresh_when(etag: @article, last_modified: @article.created_at, public: true)
+ # fresh_when(etag: @article, last_modified: @article.updated_at, public: true)
# end
#
# This will render the show template if the request isn't sending a matching ETag or
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
#
- # You can also just pass a record where +last_modified+ will be set by calling
- # +updated_at+ and the +etag+ by passing the object itself.
+ # You can also just pass a record. In this case +last_modified+ will be set
+ # by calling +updated_at+ and +etag+ by passing the object itself.
#
# def show
# @article = Article.find(params[:id])
# fresh_when(@article)
# end
#
- # When passing a record, you can still set whether the public header:
+ # You can also pass an object that responds to +maximum+, such as a
+ # collection of active records. In this case +last_modified+ will be set by
+ # calling +maximum(:updated_at)+ on the collection (the timestamp of the
+ # most recently updated record) and the +etag+ by passing the object itself.
+ #
+ # def index
+ # @articles = Article.all
+ # fresh_when(@articles)
+ # end
+ #
+ # When passing a record or a collection, you can still set the public header:
#
# def show
# @article = Article.find(params[:id])
@@ -77,18 +87,16 @@ module ActionController
#
# before_action { fresh_when @article, template: 'widgets/show' }
#
- def fresh_when(record_or_options, additional_options = {})
- if record_or_options.is_a? Hash
- options = record_or_options
- options.assert_valid_keys(:etag, :last_modified, :public, :template)
- else
- record = record_or_options
- options = { etag: record, last_modified: record.try(:updated_at) }.merge!(additional_options)
+ def fresh_when(object = nil, etag: object, last_modified: nil, public: false, template: nil)
+ last_modified ||= object.try(:updated_at) || object.try(:maximum, :updated_at)
+
+ if etag || template
+ response.etag = combine_etags(etag: etag, last_modified: last_modified,
+ public: public, template: template)
end
- response.etag = combine_etags(options) if options[:etag] || options[:template]
- response.last_modified = options[:last_modified] if options[:last_modified]
- response.cache_control[:public] = true if options[:public]
+ response.last_modified = last_modified if last_modified
+ response.cache_control[:public] = true if public
head :not_modified if request.fresh?(response)
end
@@ -115,7 +123,7 @@ module ActionController
# def show
# @article = Article.find(params[:id])
#
- # if stale?(etag: @article, last_modified: @article.created_at)
+ # if stale?(etag: @article, last_modified: @article.updated_at)
# @statistics = @article.really_expensive_call
# respond_to do |format|
# # all the supported formats
@@ -123,8 +131,8 @@ module ActionController
# end
# end
#
- # You can also just pass a record where +last_modified+ will be set by calling
- # +updated_at+ and the +etag+ by passing the object itself.
+ # You can also just pass a record. In this case +last_modified+ will be set
+ # by calling +updated_at+ and +etag+ by passing the object itself.
#
# def show
# @article = Article.find(params[:id])
@@ -137,7 +145,23 @@ module ActionController
# end
# end
#
- # When passing a record, you can still set whether the public header:
+ # You can also pass an object that responds to +maximum+, such as a
+ # collection of active records. In this case +last_modified+ will be set by
+ # calling +maximum(:updated_at)+ on the collection (the timestamp of the
+ # most recently updated record) and the +etag+ by passing the object itself.
+ #
+ # def index
+ # @articles = Article.all
+ #
+ # if stale?(@articles)
+ # @statistics = @articles.really_expensive_call
+ # respond_to do |format|
+ # # all the supported formats
+ # end
+ # end
+ # end
+ #
+ # When passing a record or a collection, you can still set the public header:
#
# def show
# @article = Article.find(params[:id])
@@ -157,8 +181,8 @@ module ActionController
# super if stale? @article, template: 'widgets/show'
# end
#
- def stale?(record_or_options, additional_options = {})
- fresh_when(record_or_options, additional_options)
+ def stale?(object = nil, etag: object, last_modified: nil, public: nil, template: nil)
+ fresh_when(object, etag: etag, last_modified: last_modified, public: public, template: template)
!request.fresh?(response)
end
@@ -191,6 +215,24 @@ module ActionController
response.cache_control.replace(:no_cache => true)
end
+ # Cache or yield the block. The cache is supposed to never expire.
+ #
+ # You can use this method when you have a HTTP response that never changes,
+ # and the browser and proxies should cache it indefinitely.
+ #
+ # * +public+: By default, HTTP responses are private, cached only on the
+ # user's web browser. To allow proxies to cache the response, set +true+ to
+ # indicate that they can serve the cached response to all users.
+ #
+ # * +version+: the version passed as a key for the cache.
+ def http_cache_forever(public: false, version: 'v1')
+ expires_in 100.years, public: public
+
+ yield if stale?(etag: "#{version}-#{request.fullpath}",
+ last_modified: Time.parse('2011-01-01').utc,
+ public: public)
+ end
+
private
def combine_etags(options)
etags = etaggers.map { |etagger| instance_exec(options, &etagger) }.compact
diff --git a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
index 3ca0c6837a..f9303efe6c 100644
--- a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
+++ b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
@@ -7,8 +7,8 @@ module ActionController
#
# config.action_controller.etag_with_template_digest = false
#
- # Override the template to digest by passing `:template` to `fresh_when`
- # and `stale?` calls. For example:
+ # Override the template to digest by passing +:template+ to +fresh_when+
+ # and +stale?+ calls. For example:
#
# # We're going to render widgets/show, not posts/show
# fresh_when @post, template: 'widgets/show'
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index 3844dbf2a6..18e003741d 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -25,7 +25,7 @@ module ActionController
end
end
- class ActionController::UrlGenerationError < RoutingError #:nodoc:
+ class ActionController::UrlGenerationError < ActionControllerError #:nodoc:
end
class MethodNotAllowed < ActionControllerError #:nodoc:
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 3d2badf9c2..0d93e2f7aa 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -29,14 +29,14 @@ module ActionController
self.status = status
self.location = url_for(location) if location
- if include_content?(self._status_code)
+ self.response_body = ""
+
+ if include_content?(self.response_code)
self.content_type = content_type || (Mime[formats.first] if formats)
self.response.charset = false if self.response
- self.response_body = " "
else
headers.delete('Content-Type')
headers.delete('Content-Length')
- self.response_body = ""
end
end
diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb
deleted file mode 100644
index af36ffa240..0000000000
--- a/actionpack/lib/action_controller/metal/hide_actions.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-
-module ActionController
- # Adds the ability to prevent public methods on a controller to be called as actions.
- module HideActions
- extend ActiveSupport::Concern
-
- included do
- class_attribute :hidden_actions
- self.hidden_actions = Set.new.freeze
- end
-
- private
-
- # Overrides AbstractController::Base#action_method? to return false if the
- # action name is in the list of hidden actions.
- def method_for_action(action_name)
- self.class.visible_action?(action_name) && super
- end
-
- module ClassMethods
- # Sets all of the actions passed in as hidden actions.
- #
- # ==== Parameters
- # * <tt>args</tt> - A list of actions
- def hide_action(*args)
- self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
- end
-
- def visible_action?(action_name)
- not hidden_actions.include?(action_name)
- end
-
- # Overrides AbstractController::Base#action_methods to remove any methods
- # that are listed as hidden methods.
- def action_methods
- @action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
- end
- end
- end
-end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 25c123edf7..20afcee537 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -53,10 +53,8 @@ module ActionController
# In your integration tests, you can do something like this:
#
# def test_access_granted_from_xml
- # get(
- # "/notes/1.xml", nil,
- # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
- # )
+ # @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
+ # get "/notes/1.xml"
#
# assert_equal 200, status
# end
@@ -108,11 +106,11 @@ module ActionController
end
def auth_scheme(request)
- request.authorization.split(' ', 2).first
+ request.authorization.to_s.split(' ', 2).first
end
def auth_param(request)
- request.authorization.split(' ', 2).second
+ request.authorization.to_s.split(' ', 2).second
end
def encode_credentials(user_name, password)
@@ -397,6 +395,7 @@ module ActionController
#
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Token
+ TOKEN_KEY = 'token='
TOKEN_REGEX = /^Token /
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
extend self
@@ -462,16 +461,22 @@ module ActionController
raw_params.map { |param| param.split %r/=(.+)?/ }
end
- # This removes the `"` characters wrapping the value.
+ # This removes the <tt>"</tt> characters wrapping the value.
def rewrite_param_values(array_params)
array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' }
end
# This method takes an authorization body and splits up the key-value
- # pairs by the standardized `:`, `;`, or `\t` delimiters defined in
- # `AUTHN_PAIR_DELIMITERS`.
+ # pairs by the standardized <tt>:</tt>, <tt>;</tt>, or <tt>\t</tt>
+ # delimiters defined in +AUTHN_PAIR_DELIMITERS+.
def raw_params(auth)
- auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
+ _raw_params = auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
+
+ if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}})
+ _raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}"
+ end
+
+ _raw_params
end
# Encodes the given token and options into an Authorization header value.
@@ -481,7 +486,7 @@ module ActionController
#
# Returns String.
def encode_credentials(token, options = {})
- values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
+ values = ["#{TOKEN_KEY}#{token.to_s.inspect}"] + options.map do |key, value|
"#{key}=#{value.to_s.inspect}"
end
"Token #{values * ", "}"
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index b0e164bc57..a3e1a71b0a 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -21,17 +21,20 @@ module ActionController
:action => self.action_name,
:params => request.filtered_parameters,
:format => request.format.try(:ref),
- :method => request.method,
+ :method => request.request_method,
:path => (request.fullpath rescue "unknown")
}
ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
- result = super
- payload[:status] = response.status
- append_info_to_payload(payload)
- result
+ begin
+ result = super
+ payload[:status] = response.status
+ result
+ ensure
+ append_info_to_payload(payload)
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
index c9ef3a3dad..7590fb6843 100644
--- a/actionpack/lib/action_controller/metal/live.rb
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -102,7 +102,7 @@ module ActionController
end
end
- message = json.gsub("\n", "\ndata: ")
+ message = json.gsub(/\n/, "\ndata: ")
@stream.write "data: #{message}\n\n"
end
end
@@ -189,12 +189,6 @@ module ActionController
!@aborted
end
- def await_close
- synchronize do
- @cv.wait_until { @closed }
- end
- end
-
def on_error(&block)
@error_callback = block
end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index dc572f13d2..7dae171215 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -1,28 +1,7 @@
-require 'active_support/core_ext/array/extract_options'
require 'abstract_controller/collector'
module ActionController #:nodoc:
module MimeResponds
- extend ActiveSupport::Concern
-
- module ClassMethods
- def respond_to(*)
- raise NoMethodError, "The controller-level `respond_to' feature has " \
- "been extracted to the `responders` gem. Add it to your Gemfile to " \
- "continue using this feature:\n" \
- " gem 'responders', '~> 2.0'\n" \
- "Consult the Rails upgrade guide for details."
- end
- end
-
- def respond_with(*)
- raise NoMethodError, "The `respond_with' feature has been extracted " \
- "to the `responders` gem. Add it to your Gemfile to continue using " \
- "this feature:\n" \
- " gem 'responders', '~> 2.0'\n" \
- "Consult the Rails upgrade guide for details."
- end
-
# Without web-service support, an action which collects the data for displaying a list of people
# might look something like this:
#
@@ -135,18 +114,6 @@ module ActionController #:nodoc:
#
# render json: @people
#
- # Since this is a common pattern, you can use the class method respond_to
- # with the respond_with method to have the same results:
- #
- # class PeopleController < ApplicationController
- # respond_to :html, :xml, :json
- #
- # def index
- # @people = Person.all
- # respond_with(@people)
- # end
- # end
- #
# Formats can have different variants.
#
# The request variant is a specialization of the request format, like <tt>:tablet</tt>,
@@ -214,13 +181,13 @@ module ActionController #:nodoc:
# format.html.phone # this gets rendered
# end
#
- # Be sure to check the documentation of +respond_with+ and
- # <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
- def respond_to(*mimes, &block)
+ # Be sure to check the documentation of <tt>ActionController::MimeResponds.respond_to</tt>
+ # for more examples.
+ def respond_to(*mimes)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
collector = Collector.new(mimes, request.variant)
- block.call(collector) if block_given?
+ yield collector if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
@@ -234,8 +201,8 @@ module ActionController #:nodoc:
# A container for responses available from the current controller for
# requests for different mime-types sent to a particular action.
#
- # The public controller methods +respond_with+ and +respond_to+ may be called
- # with a block that is used to define responses to different mime-types, e.g.
+ # The public controller methods +respond_to+ may be called with a block
+ # that is used to define responses to different mime-types, e.g.
# for +respond_to+ :
#
# respond_to do |format|
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index 2ca8955741..a7e734db42 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -1,7 +1,6 @@
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/anonymous'
-require 'active_support/core_ext/struct'
require 'action_dispatch/http/mime_type'
module ActionController
@@ -86,7 +85,7 @@ module ActionController
new name, format, include, exclude, nil, nil
end
- def initialize(name, format, include, exclude, klass, model) # nodoc
+ def initialize(name, format, include, exclude, klass, model) # :nodoc:
super
@include_set = include
@name_set = name
@@ -244,7 +243,7 @@ module ActionController
request.parameters.merge! wrapped_hash
request.request_parameters.merge! wrapped_hash
- # This will make the wrapped hash displayed in the log file
+ # This will display the wrapped hash in the log file
request.filtered_parameters.merge! wrapped_filtered_hash
end
super
@@ -252,7 +251,7 @@ module ActionController
private
- # Returns the wrapper key which will use to stored wrapped parameters.
+ # Returns the wrapper key which will be used to stored wrapped parameters.
def _wrapper_key
_wrapper_options.name
end
diff --git a/actionpack/lib/action_controller/metal/rack_delegation.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb
index 6921834044..ae9d89cc8c 100644
--- a/actionpack/lib/action_controller/metal/rack_delegation.rb
+++ b/actionpack/lib/action_controller/metal/rack_delegation.rb
@@ -6,11 +6,17 @@ module ActionController
extend ActiveSupport::Concern
delegate :headers, :status=, :location=, :content_type=,
- :status, :location, :content_type, :_status_code, :to => "@_response"
+ :status, :location, :content_type, :response_code, :to => "@_response"
- def dispatch(action, request)
+ module ClassMethods
+ def build_with_env(env = {}) #:nodoc:
+ new.tap { |c| c.set_request! ActionDispatch::Request.new(env) }
+ end
+ end
+
+ def set_request!(request) #:nodoc:
+ super
set_response!(request)
- super(action, request)
end
def response_body=(body)
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index bc94536c8c..45d3962494 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -86,8 +86,7 @@ module ActionController
# end
# end
# To use renderers and their mime types in more concise ways, see
- # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
- # <tt>ActionController::MimeResponds#respond_with</tt>
+ # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt>
def self.add(key, &block)
define_method(_render_with_renderer_method_name(key), &block)
RENDERERS << key.to_sym
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 7bbff0450a..2d15c39d88 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -4,6 +4,17 @@ module ActionController
RENDER_FORMATS_IN_PRIORITY = [:body, :text, :plain, :html]
+ module ClassMethods
+ # Documentation at ActionController::Renderer#render
+ delegate :render, to: :renderer
+
+ # Returns a renderer class (inherited from ActionController::Renderer)
+ # for the controller.
+ def renderer
+ @renderer ||= Renderer.for(self)
+ end
+ end
+
# Before processing, set the request formats in current controller formats.
def process_action(*) #:nodoc:
self.formats = request.formats.map(&:ref).compact
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index a4f376816f..367b736035 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -1,5 +1,6 @@
require 'rack/session/abstract/id'
require 'action_controller/metal/exceptions'
+require 'active_support/security_utils'
module ActionController #:nodoc:
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
@@ -28,14 +29,7 @@ module ActionController #:nodoc:
# you're building an API you'll need something like:
#
# class ApplicationController < ActionController::Base
- # protect_from_forgery
- # skip_before_action :verify_authenticity_token, if: :json_request?
- #
- # protected
- #
- # def json_request?
- # request.format.json?
- # end
+ # protect_from_forgery unless: -> { request.format.json? }
# end
#
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
@@ -86,12 +80,18 @@ module ActionController #:nodoc:
# class FooController < ApplicationController
# protect_from_forgery except: :index
#
- # You can disable CSRF protection on controller by skipping the verification before_action:
+ # You can disable forgery protection on controller by skipping the verification before_action:
# skip_before_action :verify_authenticity_token
#
# Valid Options:
#
- # * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
+ # * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. Like <tt>only: [ :create, :create_all ]</tt>.
+ # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed proc or method reference.
+ # * <tt>:prepend</tt> - By default, the verification of the authentication token is added to the front of the
+ # callback chain. If you need to make the verification depend on other callbacks, like authentication methods
+ # (say cookies vs oauth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
+ # verification callback in the position of the protect_from_forgery call. This means any callbacks added
+ # before are run first.
# * <tt>:with</tt> - Set the method to handle unverified request.
#
# Valid unverified request handling methods are:
@@ -99,9 +99,11 @@ module ActionController #:nodoc:
# * <tt>:reset_session</tt> - Resets the session.
# * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
def protect_from_forgery(options = {})
+ options = options.reverse_merge(prepend: true)
+
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
self.request_forgery_protection_token ||= :authenticity_token
- prepend_before_action :verify_authenticity_token, options
+ before_action :verify_authenticity_token, options
append_after_action :verify_same_origin_request
end
@@ -208,6 +210,7 @@ module ActionController #:nodoc:
forgery_protection_strategy.new(self).handle_unverified_request
end
+ #:nodoc:
CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
"<script> tag on another site requested protected JavaScript. " \
"If you know what you're doing, go ahead and disable forgery " \
@@ -272,7 +275,9 @@ module ActionController #:nodoc:
# session token. Essentially the inverse of
# +masked_authenticity_token+.
def valid_authenticity_token?(session, encoded_masked_token)
- return false if encoded_masked_token.nil? || encoded_masked_token.empty?
+ if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String)
+ return false
+ end
begin
masked_token = Base64.strict_decode64(encoded_masked_token)
@@ -305,8 +310,7 @@ module ActionController #:nodoc:
end
def compare_with_real_token(token, session)
- # Borrow a constant-time comparison from Rack
- Rack::Utils.secure_compare(token, real_csrf_token(session))
+ ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session))
end
def real_csrf_token(session)
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 7038f0997f..01bbd749c1 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/array/wrap'
+require 'active_support/core_ext/string/filters'
require 'active_support/deprecation'
require 'active_support/rescuable'
require 'action_dispatch/http/upload'
@@ -91,7 +92,11 @@ module ActionController
# params.permit(:c)
# # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
#
- # <tt>ActionController::Parameters</tt> is inherited from
+ # Please note that these options *are not thread-safe*. In a multi-threaded
+ # environment they should only be set once at boot-time and never mutated at
+ # runtime.
+ #
+ # <tt>ActionController::Parameters</tt> inherits from
# <tt>ActiveSupport::HashWithIndifferentAccess</tt>, this means
# that you can fetch values using either <tt>:key</tt> or <tt>"key"</tt>.
#
@@ -114,10 +119,12 @@ module ActionController
def self.const_missing(const_name)
super unless const_name == :NEVER_UNPERMITTED_PARAMS
- ActiveSupport::Deprecation.warn "`ActionController::Parameters::NEVER_UNPERMITTED_PARAMS`"\
- " has been deprecated. Use "\
- "`ActionController::Parameters.always_permitted_parameters` instead."
- self.always_permitted_parameters
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ `ActionController::Parameters::NEVER_UNPERMITTED_PARAMS` has been deprecated.
+ Use `ActionController::Parameters.always_permitted_parameters` instead.
+ MSG
+
+ always_permitted_parameters
end
# Returns a new instance of <tt>ActionController::Parameters</tt>.
@@ -160,6 +167,12 @@ module ActionController
end
end
+ # Returns an unsafe, unfiltered +Hash+ representation of this parameter.
+ def to_unsafe_h
+ to_hash
+ end
+ alias_method :to_unsafe_hash, :to_unsafe_h
+
# Convert all hashes in values into parameters, then yield each pair like
# the same way as <tt>Hash#each_pair</tt>
def each_pair(&block)
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index dd8da4b5dc..d01927b7cb 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -24,7 +24,7 @@ module ActionController
module ClassMethods
def before_filters
- _process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
+ _process_action_callbacks.find_all{|x| x.kind == :before}.map(&:name)
end
end
end
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index 0f2fa5fb08..572d1770f7 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -30,9 +30,9 @@ module ActionController
:_recall => request.path_parameters
}.merge!(super).freeze
- if (same_origin = _routes.equal?(env["action_dispatch.routes".freeze])) ||
- (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
- (original_script_name = env['ORIGINAL_SCRIPT_NAME'.freeze])
+ if (same_origin = _routes.equal?(request.routes)) ||
+ (script_name = request.engine_script_name(_routes)) ||
+ (original_script_name = request.original_script_name)
options = @_url_options.dup
if original_script_name
diff --git a/actionpack/lib/action_controller/model_naming.rb b/actionpack/lib/action_controller/model_naming.rb
deleted file mode 100644
index 2b33f67263..0000000000
--- a/actionpack/lib/action_controller/model_naming.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-module ActionController
- module ModelNaming
- # Converts the given object to an ActiveModel compliant one.
- def convert_to_model(object)
- object.respond_to?(:to_model) ? object.to_model : object
- end
-
- def model_name_from_record_or_class(record_or_class)
- convert_to_model(record_or_class).model_name
- end
- end
-end
diff --git a/actionpack/lib/action_controller/renderer.rb b/actionpack/lib/action_controller/renderer.rb
new file mode 100644
index 0000000000..e8b29c5b5e
--- /dev/null
+++ b/actionpack/lib/action_controller/renderer.rb
@@ -0,0 +1,100 @@
+require 'active_support/core_ext/hash/keys'
+
+module ActionController
+ # ActionController::Renderer allows to render arbitrary templates
+ # without requirement of being in controller actions.
+ #
+ # You get a concrete renderer class by invoking ActionController::Base#renderer.
+ # For example,
+ #
+ # ApplicationController.renderer
+ #
+ # It allows you to call method #render directly.
+ #
+ # ApplicationController.renderer.render template: '...'
+ #
+ # You can use a shortcut on controller to replace previous example with:
+ #
+ # ApplicationController.render template: '...'
+ #
+ # #render method allows you to use any options as when rendering in controller.
+ # For example,
+ #
+ # FooController.render :action, locals: { ... }, assigns: { ... }
+ #
+ # The template will be rendered in a Rack environment which is accessible through
+ # ActionController::Renderer#env. You can set it up in two ways:
+ #
+ # * by changing renderer defaults, like
+ #
+ # ApplicationController.renderer.defaults # => hash with default Rack environment
+ #
+ # * by initializing an instance of renderer by passing it a custom environment.
+ #
+ # ApplicationController.renderer.new(method: 'post', https: true)
+ #
+ class Renderer
+ class_attribute :controller, :defaults
+ # Rack environment to render templates in.
+ attr_reader :env
+
+ class << self
+ delegate :render, to: :new
+
+ # Create a new renderer class for a specific controller class.
+ def for(controller)
+ Class.new self do
+ self.controller = controller
+ self.defaults = {
+ http_host: 'example.org',
+ https: false,
+ method: 'get',
+ script_name: '',
+ 'rack.input' => ''
+ }
+ end
+ end
+ end
+
+ # Accepts a custom Rack environment to render templates in.
+ # It will be merged with ActionController::Renderer.defaults
+ def initialize(env = {})
+ @env = normalize_keys(defaults).merge normalize_keys(env)
+ @env['action_dispatch.routes'] = controller._routes
+ end
+
+ # Render templates with any options from ActionController::Base#render_to_string.
+ def render(*args)
+ raise 'missing controller' unless controller?
+
+ instance = controller.build_with_env(env)
+ instance.render_to_string(*args)
+ end
+
+ private
+ def normalize_keys(env)
+ http_header_format(env).tap do |new_env|
+ handle_method_key! new_env
+ handle_https_key! new_env
+ end
+ end
+
+ def http_header_format(env)
+ env.transform_keys do |key|
+ key.is_a?(Symbol) ? key.to_s.upcase : key
+ end
+ end
+
+ def handle_method_key!(env)
+ if method = env.delete('METHOD')
+ env['REQUEST_METHOD'] = method.upcase
+ end
+ end
+
+ def handle_https_key!(env)
+ if env.has_key? 'HTTPS'
+ env['HTTPS'] = env['HTTPS'] ? 'on' : 'off'
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 41d33d4396..4782991463 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -66,7 +66,10 @@ module ActionController
def reset_template_assertion
RENDER_TEMPLATE_INSTANCE_VARIABLES.each do |instance_variable|
- instance_variable_get("@_#{instance_variable}").clear
+ ivar_name = "@_#{instance_variable}"
+ if instance_variable_defined?(ivar_name)
+ instance_variable_get(ivar_name).clear
+ end
end
end
@@ -144,6 +147,8 @@ module ActionController
assert(@_layouts.keys.any? {|l| l =~ expected_layout }, msg)
when nil, false
assert(@_layouts.empty?, msg)
+ else
+ raise ArgumentError, "assert_template only accepts a String, Symbol, Regexp, nil or false for :layout"
end
end
@@ -489,55 +494,66 @@ module ActionController
# Simulate a GET request with the given parameters.
#
# - +action+: The controller action to call.
- # - +parameters+: The HTTP parameters that you want to pass. This may
- # be +nil+, a hash, or a string that is appropriately encoded
+ # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
+ # - +body+: The request body with a string that is appropriately encoded
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
# - +session+: A hash of parameters to store in the session. This may be +nil+.
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
#
# You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
# +post+, +patch+, +put+, +delete+, and +head+.
+ # Example sending parameters, session and setting a flash message:
+ #
+ # get :show,
+ # params: { id: 7 },
+ # session: { user_id: 1 },
+ # flash: { notice: 'This is flash message' }
#
# Note that the request method is not verified. The different methods are
# available to make the tests more expressive.
def get(action, *args)
- process(action, "GET", *args)
+ process_with_kwargs("GET", action, *args)
end
# Simulate a POST request with the given parameters and set/volley the response.
# See +get+ for more details.
def post(action, *args)
- process(action, "POST", *args)
+ process_with_kwargs("POST", action, *args)
end
# Simulate a PATCH request with the given parameters and set/volley the response.
# See +get+ for more details.
def patch(action, *args)
- process(action, "PATCH", *args)
+ process_with_kwargs("PATCH", action, *args)
end
# Simulate a PUT request with the given parameters and set/volley the response.
# See +get+ for more details.
def put(action, *args)
- process(action, "PUT", *args)
+ process_with_kwargs("PUT", action, *args)
end
# Simulate a DELETE request with the given parameters and set/volley the response.
# See +get+ for more details.
def delete(action, *args)
- process(action, "DELETE", *args)
+ process_with_kwargs("DELETE", action, *args)
end
# Simulate a HEAD request with the given parameters and set/volley the response.
# See +get+ for more details.
def head(action, *args)
- process(action, "HEAD", *args)
+ process_with_kwargs("HEAD", action, *args)
end
- def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
+ def xml_http_request(*args)
+ ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
+ xhr and xml_http_request methods are deprecated in favor of
+ `get :index, xhr: true` and `post :create, xhr: true`
+ MSG
+
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
- @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
- __send__(request_method, action, parameters, session, flash).tap do
+ @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ __send__(*args).tap do
@request.env.delete 'HTTP_X_REQUESTED_WITH'
@request.env.delete 'HTTP_ACCEPT'
end
@@ -561,41 +577,69 @@ module ActionController
# parameters and set/volley the response.
#
# - +action+: The controller action to call.
- # - +http_method+: Request method used to send the http request. Possible values
- # are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+.
- # - +parameters+: The HTTP parameters. This may be +nil+, a hash, or a
- # string that is appropriately encoded (+application/x-www-form-urlencoded+
- # or +multipart/form-data+).
+ # - +method+: Request method used to send the HTTP request. Possible values
+ # are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+. Can be a symbol.
+ # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
+ # - +body+: The request body with a string that is appropriately encoded
+ # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
# - +session+: A hash of parameters to store in the session. This may be +nil+.
# - +flash+: A hash of parameters to store in the flash. This may be +nil+.
+ # - +format+: Request format. Defaults to +nil+. Can be string or symbol.
#
# Example calling +create+ action and sending two params:
#
- # process :create, 'POST', user: { name: 'Gaurish Sharma', email: 'user@example.com' }
- #
- # Example sending parameters, +nil+ session and setting a flash message:
- #
- # process :view, 'GET', { id: 7 }, nil, { notice: 'This is flash message' }
+ # process :create,
+ # method: 'POST',
+ # params: {
+ # user: { name: 'Gaurish Sharma', email: 'user@example.com' }
+ # },
+ # session: { user_id: 1 },
+ # flash: { notice: 'This is flash message' }
#
# To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests
# prefer using #get, #post, #patch, #put, #delete and #head methods
# respectively which will make tests more expressive.
#
# Note that the request method is not verified.
- def process(action, http_method = 'GET', *args)
+ def process(action, *args)
check_required_ivars
- if args.first.is_a?(String) && http_method != 'HEAD'
- @request.env['RAW_POST_DATA'] = args.shift
+ if kwarg_request?(*args)
+ parameters, session, body, flash, http_method, format, xhr = args[0].values_at(:params, :session, :body, :flash, :method, :format, :xhr)
+ else
+ http_method, parameters, session, flash = args
+ format = nil
+
+ if parameters.is_a?(String) && http_method != 'HEAD'
+ body = parameters
+ parameters = nil
+ end
+
+ if parameters.present? || session.present? || flash.present?
+ non_kwarg_request_warning
+ end
+ end
+
+ if body.present?
+ @request.env['RAW_POST_DATA'] = body
+ end
+
+ if http_method.present?
+ http_method = http_method.to_s.upcase
+ else
+ http_method = "GET"
end
- parameters, session, flash = args
parameters ||= {}
# Ensure that numbers and symbols passed as params are converted to
# proper params, as is the case when engaging rack.
parameters = paramify_values(parameters) if html_format?(parameters)
+ if format.present?
+ parameters[:format] = format
+ end
+
@html_document = nil
unless @controller.respond_to?(:recycle!)
@@ -617,6 +661,11 @@ module ActionController
@request.session.update(session) if session
@request.flash.update(flash || {})
+ if xhr
+ @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
+ @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ end
+
@controller.request = @request
@controller.response = @response
@@ -638,6 +687,13 @@ module ActionController
if flash_value = @request.flash.to_session_value
@request.session['flash'] = flash_value
+ else
+ @request.session.delete('flash')
+ end
+
+ if xhr
+ @request.env.delete 'HTTP_X_REQUESTED_WITH'
+ @request.env.delete 'HTTP_ACCEPT'
end
@response
@@ -688,8 +744,40 @@ module ActionController
private
+ def process_with_kwargs(http_method, action, *args)
+ if kwarg_request?(*args)
+ args.first.merge!(method: http_method)
+ process(action, *args)
+ else
+ non_kwarg_request_warning if args.present?
+
+ args = args.unshift(http_method)
+ process(action, *args)
+ end
+ end
+
+ REQUEST_KWARGS = %i(params session flash method body xhr)
+ def kwarg_request?(*args)
+ args[0].respond_to?(:keys) && (
+ (args[0].key?(:format) && args[0].keys.size == 1) ||
+ args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
+ )
+ end
+
+ def non_kwarg_request_warning
+ ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
+ ActionController::TestCase HTTP request methods will accept only
+ keyword arguments in future Rails versions.
+
+ Examples:
+
+ get :show, params: { id: 1 }, session: { user_id: 1 }
+ process :update, method: :post, params: { id: 1 }
+ MSG
+ end
+
def document_root_element
- html_document
+ html_document.root
end
def check_required_ivars
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 11b5e6be33..dcd3ee0644 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2014 David Heinemeier Hansson
+# Copyright (c) 2004-2015 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 63a3cbc90b..747d295261 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -69,17 +69,17 @@ module ActionDispatch
end
def date
- if date_header = headers['Date']
+ if date_header = headers[DATE]
Time.httpdate(date_header)
end
end
def date?
- headers.include?('Date')
+ headers.include?(DATE)
end
def date=(utc_time)
- headers['Date'] = utc_time.httpdate
+ headers[DATE] = utc_time.httpdate
end
def etag=(etag)
@@ -89,6 +89,7 @@ module ActionDispatch
private
+ DATE = 'Date'.freeze
LAST_MODIFIED = "Last-Modified".freeze
ETAG = "ETag".freeze
CACHE_CONTROL = "Cache-Control".freeze
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index 9c8f65deac..53a98c5d0a 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -72,11 +72,12 @@ module ActionDispatch
end
end
end
+
# Sets the \variant for template.
def variant=(variant)
if variant.is_a?(Symbol)
@variant = [variant]
- elsif variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
+ elsif variant.nil? || variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
@variant = variant
else
raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index b9d5009683..047a17937a 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -6,7 +6,7 @@ require 'active_support/core_ext/string/starts_ends_with'
module Mime
class Mimes < Array
def symbols
- @symbols ||= map { |m| m.to_sym }
+ @symbols ||= map(&:to_sym)
end
%w(<< concat shift unshift push pop []= clear compact! collect!
diff --git a/actionpack/lib/action_dispatch/http/parameter_filter.rb b/actionpack/lib/action_dispatch/http/parameter_filter.rb
index b655a54865..df4b073a17 100644
--- a/actionpack/lib/action_dispatch/http/parameter_filter.rb
+++ b/actionpack/lib/action_dispatch/http/parameter_filter.rb
@@ -56,7 +56,7 @@ module ActionDispatch
elsif value.is_a?(Array)
value = value.map { |v| v.is_a?(Hash) ? call(v) : v }
elsif blocks.any?
- key = key.dup
+ key = key.dup if key.duplicable?
value = value.dup if value.duplicable?
blocks.each { |b| b.call(key, value) }
end
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index 20ae48d458..c2f05ecc86 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/indifferent_access'
-require 'active_support/deprecation'
module ActionDispatch
module Http
@@ -25,13 +24,6 @@ module ActionDispatch
@env[PARAMETERS_KEY] = parameters
end
- def symbolized_path_parameters
- ActiveSupport::Deprecation.warn(
- "`symbolized_path_parameters` is deprecated. Please use `path_parameters`"
- )
- path_parameters
- end
-
# Returns a hash with the \parameters used to form the \path of the request.
# Returned hash keys are strings:
#
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index e854dd266c..cadbfc88cb 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -105,6 +105,18 @@ module ActionDispatch
@request_method ||= check_method(env["REQUEST_METHOD"])
end
+ def routes # :nodoc:
+ env["action_dispatch.routes".freeze]
+ end
+
+ def original_script_name # :nodoc:
+ env['ORIGINAL_SCRIPT_NAME'.freeze]
+ end
+
+ def engine_script_name(_routes) # :nodoc:
+ env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]
+ end
+
def request_method=(request_method) #:nodoc:
if check_method(request_method)
@request_method = env["REQUEST_METHOD"] = request_method
@@ -325,15 +337,6 @@ module ActionDispatch
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
end
- # Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility.
- def deep_munge(hash)
- ActiveSupport::Deprecation.warn(
- "This method has been extracted into ActionDispatch::Request::Utils.deep_munge. Please start using that instead."
- )
-
- Utils.deep_munge(hash)
- end
-
protected
def parse_query(qs)
Utils.deep_munge(super)
@@ -341,7 +344,7 @@ module ActionDispatch
private
def check_method(name)
- HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
+ HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS[0...-1].join(', ')}, and #{HTTP_METHODS[-1]}")
name
end
end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index c5e18048da..4061ea71a3 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/deprecation'
require 'action_dispatch/http/filter_redirect'
require 'monitor'
@@ -283,15 +282,6 @@ module ActionDispatch # :nodoc:
end
alias prepare! to_a
- # Be super clear that a response object is not an Array. Defining this
- # would make implicit splatting work, but it also makes adding responses
- # as arrays work, and "flattening" responses, cascading to the rack body!
- # Not sensible behavior.
- def to_ary
- ActiveSupport::Deprecation.warn 'ActionDispatch::Response#to_ary no longer performs implicit conversion to an Array. Please use response.to_a instead, or a splat like `status, headers, body = *response`'
- to_a
- end
-
# Returns the response cookies, converted to a Hash of (name => value) pairs
#
# assert_equal 'AuthorOfNewPage', r.cookies['author']
@@ -309,9 +299,6 @@ module ActionDispatch # :nodoc:
cookies
end
- def _status_code
- @status
- end
private
def before_committed
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 6b8dcaf497..001b14ec97 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -12,10 +12,22 @@ module ActionDispatch
self.tld_length = 1
class << self
+ # Returns the domain part of a host given the domain level.
+ #
+ # # Top-level domain example
+ # extract_domain('www.example.com', 1) # => "example.com"
+ # # Second-level domain example
+ # extract_domain('dev.www.example.co.uk', 2) # => "example.co.uk"
def extract_domain(host, tld_length)
extract_domain_from(host, tld_length) if named_host?(host)
end
+ # Returns the subdomains of a host as an Array given the domain level.
+ #
+ # # Top-level domain example
+ # extract_subdomains('www.example.com', 1) # => ["www"]
+ # # Second-level domain example
+ # extract_subdomains('dev.www.example.co.uk', 2) # => ["dev", "www"]
def extract_subdomains(host, tld_length)
if named_host?(host)
extract_subdomains_from(host, tld_length)
@@ -24,6 +36,12 @@ module ActionDispatch
end
end
+ # Returns the subdomains of a host as a String given the domain level.
+ #
+ # # Top-level domain example
+ # extract_subdomain('www.example.com', 1) # => "www"
+ # # Second-level domain example
+ # extract_subdomain('dev.www.example.co.uk', 2) # => "dev.www"
def extract_subdomain(host, tld_length)
extract_subdomains(host, tld_length).join('.')
end
@@ -68,7 +86,9 @@ module ActionDispatch
end
def add_anchor(path, anchor)
- path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param.to_s)}"
+ if anchor
+ path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}"
+ end
end
def extract_domain_from(host, tld_length)
@@ -171,16 +191,43 @@ module ActionDispatch
end
# Returns the complete URL used for this request.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com'
+ # req.url # => "http://example.com"
def url
protocol + host_with_port + fullpath
end
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com'
+ # req.protocol # => "http://"
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com', 'HTTPS' => 'on'
+ # req.protocol # => "https://"
def protocol
@protocol ||= ssl? ? 'https://' : 'http://'
end
# Returns the \host for this request, such as "example.com".
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com'
+ # req.raw_host_with_port # => "example.com"
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.raw_host_with_port # => "example.com:8080"
def raw_host_with_port
if forwarded = env["HTTP_X_FORWARDED_HOST"]
forwarded.split(/,\s?/).last
@@ -190,17 +237,44 @@ module ActionDispatch
end
# Returns the host for this request, such as example.com.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.host # => "example.com"
def host
raw_host_with_port.sub(/:\d+$/, '')
end
# Returns a \host:\port string for this request, such as "example.com" or
# "example.com:8080".
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:80'
+ # req.host_with_port # => "example.com"
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.host_with_port # => "example.com:8080"
def host_with_port
"#{host}#{port_string}"
end
# Returns the port number of this request as an integer.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com'
+ # req.port # => 80
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.port # => 8080
def port
@port ||= begin
if raw_host_with_port =~ /:(\d+)$/
@@ -212,6 +286,13 @@ module ActionDispatch
end
# Returns the standard \port number for this request's protocol.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.standard_port # => 80
def standard_port
case protocol
when 'https://' then 443
@@ -220,18 +301,48 @@ module ActionDispatch
end
# Returns whether this request is using the standard port
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:80'
+ # req.standard_port? # => true
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.standard_port? # => false
def standard_port?
port == standard_port
end
# Returns a number \port suffix like 8080 if the \port number of this request
# is not the default HTTP \port 80 or HTTPS \port 443.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:80'
+ # req.optional_port # => nil
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.optional_port # => 8080
def optional_port
standard_port? ? nil : port
end
# Returns a string \port suffix, including colon, like ":8080" if the \port
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
+ #
+ # class Request < Rack::Request
+ # include ActionDispatch::Http::URL
+ # end
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:80'
+ # req.port_string # => ""
+ #
+ # req = Request.new 'HTTP_HOST' => 'example.com:8080'
+ # req.port_string # => ":8080"
def port_string
standard_port? ? '' : ":#{port}"
end
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index 59b353b1b7..992c1a9efe 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -40,7 +40,7 @@ module ActionDispatch
end
message = "No route matches #{Hash[constraints.sort].inspect}"
- message << " missing required keys: #{missing_keys.sort.inspect}" if name
+ message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty?
raise ActionController::UrlGenerationError, message
end
diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
index 990d2127ee..d7ce6042c2 100644
--- a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
+++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
@@ -88,13 +88,13 @@ module ActionDispatch
erb = File.read File.join(viz_dir, 'index.html.erb')
states = "function tt() { return #{to_json}; }"
- fun_routes = paths.shuffle.first(3).map do |ast|
+ fun_routes = paths.sample(3).map do |ast|
ast.map { |n|
case n
when Nodes::Symbol
case n.left
when ':id' then rand(100).to_s
- when ':format' then %w{ xml json }.shuffle.first
+ when ':format' then %w{ xml json }.sample
else
'omg'
end
@@ -109,7 +109,7 @@ module ActionDispatch
svg = to_svg
javascripts = [states, fsm_js]
- # Annoying hack for 1.9 warnings
+ # Annoying hack warnings
fun_routes = fun_routes
stylesheets = stylesheets
svg = svg
diff --git a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
index 66e414213a..0ccab21801 100644
--- a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
+++ b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
@@ -45,51 +45,6 @@ module ActionDispatch
(@table.keys + @table.values.flat_map(&:keys)).uniq
end
- # Returns a generalized transition graph with reduced states. The states
- # are reduced like a DFA, but the table must be simulated like an NFA.
- #
- # Edges of the GTG are regular expressions.
- def generalized_table
- gt = GTG::TransitionTable.new
- marked = {}
- state_id = Hash.new { |h,k| h[k] = h.length }
- alphabet = self.alphabet
-
- stack = [eclosure(0)]
-
- until stack.empty?
- state = stack.pop
- next if marked[state] || state.empty?
-
- marked[state] = true
-
- alphabet.each do |alpha|
- next_state = eclosure(following_states(state, alpha))
- next if next_state.empty?
-
- gt[state_id[state], state_id[next_state]] = alpha
- stack << next_state
- end
- end
-
- final_groups = state_id.keys.find_all { |s|
- s.sort.last == accepting
- }
-
- final_groups.each do |states|
- id = state_id[states]
-
- gt.add_accepting(id)
- save = states.find { |s|
- @memos.key?(s) && eclosure(s).sort.last == accepting
- }
-
- gt.add_memo(id, memo(save))
- end
-
- gt
- end
-
# Returns set of NFA states to which there is a transition on ast symbol
# +a+ from some state +s+ in +t+.
def following_states(t, a)
@@ -107,7 +62,7 @@ module ActionDispatch
end
def alphabet
- inverted.values.flat_map(&:keys).compact.uniq.sort_by { |x| x.to_s }
+ inverted.values.flat_map(&:keys).compact.uniq.sort_by(&:to_s)
end
# Returns a set of NFA states reachable from some NFA state +s+ in set
diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb
index 3af940a02f..64b48ca45f 100644
--- a/actionpack/lib/action_dispatch/journey/path/pattern.rb
+++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb
@@ -42,7 +42,7 @@ module ActionDispatch
end
def names
- @names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
+ @names ||= spec.grep(Nodes::Symbol).map(&:name)
end
def required_names
@@ -52,7 +52,7 @@ module ActionDispatch
def optional_names
@optional_names ||= spec.grep(Nodes::Group).flat_map { |group|
group.grep(Nodes::Symbol)
- }.map { |n| n.name }.uniq
+ }.map(&:name).uniq
end
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
@@ -122,6 +122,11 @@ module ActionDispatch
re = @matchers[node.left.to_sym] || '.+'
"(#{re})"
end
+
+ def visit_OR(node)
+ children = node.children.map { |n| visit n }
+ "(?:#{children.join(?|)})"
+ end
end
class UnanchoredRegexp < AnchoredRegexp # :nodoc:
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 9f0a3af902..4d5c18984a 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -60,7 +60,7 @@ module ActionDispatch
end
def parts
- @parts ||= segments.map { |n| n.to_sym }
+ @parts ||= segments.map(&:to_sym)
end
alias :segment_keys :parts
@@ -68,12 +68,8 @@ module ActionDispatch
@path_formatter.evaluate path_options
end
- def optional_parts
- path.optional_names.map { |n| n.to_sym }
- end
-
def required_parts
- @required_parts ||= path.required_names.map { |n| n.to_sym }
+ @required_parts ||= path.required_names.map(&:to_sym)
end
def required_default?(key)
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index 9131b65380..e9df984c86 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -68,8 +68,8 @@ module ActionDispatch
def visualizer
tt = GTG::Builder.new(ast).transition_table
- groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
- asts = groups.values.map { |v| v.first }
+ groups = partitioned_routes.first.map(&:ast).group_by(&:to_s)
+ asts = groups.values.map(&:first)
tt.visualizer(asts)
end
@@ -121,6 +121,7 @@ module ActionDispatch
end
def match_head_routes(routes, req)
+ routes.delete_if { |route| route.verb == // }
head_routes = match_routes(routes, req)
if head_routes.empty?
diff --git a/actionpack/lib/action_dispatch/journey/scanner.rb b/actionpack/lib/action_dispatch/journey/scanner.rb
index 633be11a2d..19e0bc03d6 100644
--- a/actionpack/lib/action_dispatch/journey/scanner.rb
+++ b/actionpack/lib/action_dispatch/journey/scanner.rb
@@ -39,18 +39,18 @@ module ActionDispatch
[:SLASH, text]
when text = @ss.scan(/\*\w+/)
[:STAR, text]
- when text = @ss.scan(/\(/)
+ when text = @ss.scan(/(?<!\\)\(/)
[:LPAREN, text]
- when text = @ss.scan(/\)/)
+ when text = @ss.scan(/(?<!\\)\)/)
[:RPAREN, text]
when text = @ss.scan(/\|/)
[:OR, text]
when text = @ss.scan(/\./)
[:DOT, text]
- when text = @ss.scan(/:\w+/)
+ when text = @ss.scan(/(?<!\\):\w+/)
[:SYMBOL, text]
- when text = @ss.scan(/[\w%\-~]+/)
- [:LITERAL, text]
+ when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\:|\\\(|\\\))+/)
+ [:LITERAL, text.tr('\\', '')]
# any char
when text = @ss.scan(/./)
[:LITERAL, text]
diff --git a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
index 50caebaa18..403e16a7bb 100644
--- a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
+++ b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
@@ -16,10 +16,6 @@ h2 {
font-size: 0.5em;
}
-div#chart-2 {
- height: 350px;
-}
-
.clearfix {display: inline-block; }
.input { overflow: show;}
.instruction { color: #666; padding: 0 30px 20px; font-size: 0.9em}
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index baf9d5779e..f80df78582 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,6 +1,6 @@
module ActionDispatch
- # Provide callbacks to be executed before and after the request dispatch.
+ # Provides callbacks to be executed before and after dispatching the request.
class Callbacks
include ActiveSupport::Callbacks
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 83ac62a83d..b7687ca100 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -71,11 +71,13 @@ module ActionDispatch
# restrict to the domain level. If you use a schema like www.example.com
# and want to share session with user.example.com set <tt>:domain</tt>
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
- # <tt>:all</tt> again when deleting cookies.
+ # <tt>:all</tt> or <tt>Array</tt> again when deleting cookies.
#
- # domain: nil # Does not sets cookie domain. (default)
+ # domain: nil # Does not set cookie domain. (default)
# domain: :all # Allow the cookie for the top most level
# # domain and subdomains.
+ # domain: %w(.example.com .example.org) # Allow the cookie
+ # # for concrete domain names.
#
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
@@ -120,7 +122,7 @@ module ActionDispatch
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
# cookie was tampered with by the user (or a 3rd party), nil will be returned.
#
- # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
# legacy cookies signed with the old key generator will be transparently upgraded.
#
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
@@ -143,7 +145,7 @@ module ActionDispatch
# Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
# If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
#
- # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
# legacy cookies signed with the old key generator will be transparently upgraded.
#
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
@@ -281,7 +283,7 @@ module ActionDispatch
def handle_options(options) #:nodoc:
options[:path] ||= "/"
- if options[:domain] == :all
+ if options[:domain] == :all || options[:domain] == 'all'
# if there is a provided tld length then we use it otherwise default domain regexp
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
@@ -408,7 +410,7 @@ module ActionDispatch
@options[:serializer] == :hybrid && value.start_with?(MARSHAL_SIGNATURE)
end
- def serialize(name, value)
+ def serialize(value)
serializer.dump(value)
end
@@ -461,9 +463,9 @@ module ActionDispatch
def []=(name, options)
if options.is_a?(Hash)
options.symbolize_keys!
- options[:value] = @verifier.generate(serialize(name, options[:value]))
+ options[:value] = @verifier.generate(serialize(options[:value]))
else
- options = { :value => @verifier.generate(serialize(name, options)) }
+ options = { :value => @verifier.generate(serialize(options)) }
end
raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
@@ -479,7 +481,7 @@ module ActionDispatch
end
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
- # config.secret_token and secrets.secret_key_base are both set. It reads
+ # secrets.secret_token and secrets.secret_key_base are both set. It reads
# legacy cookies signed with the old dummy key generator and re-saves
# them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
@@ -522,7 +524,7 @@ module ActionDispatch
options = { :value => options }
end
- options[:value] = @encryptor.encrypt_and_sign(serialize(name, options[:value]))
+ options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
@parent_jar[name] = options
@@ -537,7 +539,7 @@ module ActionDispatch
end
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
- # instead of EncryptedCookieJar if config.secret_token and secrets.secret_key_base
+ # instead of EncryptedCookieJar if secrets.secret_token and secrets.secret_key_base
# are both set. It reads legacy cookies signed with the old dummy key generator and
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index 274f6f2f22..9082aac271 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -1,6 +1,10 @@
require 'action_dispatch/http/request'
require 'action_dispatch/middleware/exception_wrapper'
require 'action_dispatch/routing/inspector'
+require 'action_view'
+require 'action_view/base'
+
+require 'pp'
module ActionDispatch
# This middleware is responsible for logging exceptions and
@@ -8,6 +12,32 @@ module ActionDispatch
class DebugExceptions
RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__)
+ class DebugView < ActionView::Base
+ def debug_params(params)
+ clean_params = params.clone
+ clean_params.delete("action")
+ clean_params.delete("controller")
+
+ if clean_params.empty?
+ 'None'
+ else
+ PP.pp(clean_params, "", 200)
+ end
+ end
+
+ def debug_headers(headers)
+ if headers.present?
+ headers.inspect.gsub(',', ",\n")
+ else
+ 'None'
+ end
+ end
+
+ def debug_hash(object)
+ object.to_hash.sort_by { |k, _| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n")
+ end
+ end
+
def initialize(app, routes_app = nil)
@app = app
@routes_app = routes_app
@@ -35,12 +65,25 @@ module ActionDispatch
if env['action_dispatch.show_detailed_exceptions']
request = Request.new(env)
- template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
+ traces = wrapper.traces
+
+ trace_to_show = 'Application Trace'
+ if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error'
+ trace_to_show = 'Full Trace'
+ end
+
+ if source_to_show = traces[trace_to_show].first
+ source_to_show_id = source_to_show[:id]
+ end
+
+ template = DebugView.new([RESCUES_TEMPLATE_PATH],
request: request,
exception: wrapper.exception,
- traces: traces_from_wrapper(wrapper),
+ traces: traces,
+ show_source_idx: source_to_show_id,
+ trace_to_show: trace_to_show,
routes_inspector: routes_inspector(exception),
- source_extract: wrapper.source_extract,
+ source_extracts: wrapper.source_extracts,
line_number: wrapper.line_number,
file: wrapper.file
)
@@ -93,36 +136,5 @@ module ActionDispatch
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
end
end
-
- # Augment the exception traces by providing ids for all unique stack frame
- def traces_from_wrapper(wrapper)
- application_trace = wrapper.application_trace
- framework_trace = wrapper.framework_trace
- full_trace = wrapper.full_trace
-
- if application_trace && framework_trace
- id_counter = 0
-
- application_trace = application_trace.map do |trace|
- prev = id_counter
- id_counter += 1
- { id: prev, trace: trace }
- end
-
- framework_trace = framework_trace.map do |trace|
- prev = id_counter
- id_counter += 1
- { id: prev, trace: trace }
- end
-
- full_trace = application_trace + framework_trace
- end
-
- {
- "Application Trace" => application_trace,
- "Framework Trace" => framework_trace,
- "Full Trace" => full_trace
- }
- end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
index b98b553c38..d176a73633 100644
--- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
+++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
@@ -1,21 +1,23 @@
require 'action_controller/metal/exceptions'
require 'active_support/core_ext/module/attribute_accessors'
+require 'rack/utils'
module ActionDispatch
class ExceptionWrapper
cattr_accessor :rescue_responses
@@rescue_responses = Hash.new(:internal_server_error)
@@rescue_responses.merge!(
- 'ActionController::RoutingError' => :not_found,
- 'AbstractController::ActionNotFound' => :not_found,
- 'ActionController::MethodNotAllowed' => :method_not_allowed,
- 'ActionController::UnknownHttpMethod' => :method_not_allowed,
- 'ActionController::NotImplemented' => :not_implemented,
- 'ActionController::UnknownFormat' => :not_acceptable,
- 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
- 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
- 'ActionController::BadRequest' => :bad_request,
- 'ActionController::ParameterMissing' => :bad_request
+ 'ActionController::RoutingError' => :not_found,
+ 'AbstractController::ActionNotFound' => :not_found,
+ 'ActionController::MethodNotAllowed' => :method_not_allowed,
+ 'ActionController::UnknownHttpMethod' => :method_not_allowed,
+ 'ActionController::NotImplemented' => :not_implemented,
+ 'ActionController::UnknownFormat' => :not_acceptable,
+ 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
+ 'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity,
+ 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
+ 'ActionController::BadRequest' => :bad_request,
+ 'ActionController::ParameterMissing' => :bad_request
)
cattr_accessor :rescue_templates
@@ -56,24 +58,51 @@ module ActionDispatch
clean_backtrace(:all)
end
+ def traces
+ appplication_trace_with_ids = []
+ framework_trace_with_ids = []
+ full_trace_with_ids = []
+
+ full_trace.each_with_index do |trace, idx|
+ trace_with_id = { id: idx, trace: trace }
+
+ if application_trace.include?(trace)
+ appplication_trace_with_ids << trace_with_id
+ else
+ framework_trace_with_ids << trace_with_id
+ end
+
+ full_trace_with_ids << trace_with_id
+ end
+
+ {
+ "Application Trace" => appplication_trace_with_ids,
+ "Framework Trace" => framework_trace_with_ids,
+ "Full Trace" => full_trace_with_ids
+ }
+ end
+
def self.status_code_for_exception(class_name)
Rack::Utils.status_code(@@rescue_responses[class_name])
end
- def source_extract
- exception.backtrace.map do |trace|
- file, line = trace.split(":")
- line_number = line.to_i
+ def source_extracts
+ backtrace.map do |trace|
+ file, line_number = extract_file_and_line_number(trace)
+
{
code: source_fragment(file, line_number),
- file: file,
line_number: line_number
}
- end if exception.backtrace
+ end
end
private
+ def backtrace
+ Array(@exception.backtrace)
+ end
+
def original_exception(exception)
if registered_original_exception?(exception)
exception.original_exception
@@ -88,9 +117,9 @@ module ActionDispatch
def clean_backtrace(*args)
if backtrace_cleaner
- backtrace_cleaner.clean(@exception.backtrace, *args)
+ backtrace_cleaner.clean(backtrace, *args)
else
- @exception.backtrace
+ backtrace
end
end
@@ -110,6 +139,13 @@ module ActionDispatch
end
end
+ def extract_file_and_line_number(trace)
+ # Split by the first colon followed by some digits, which works for both
+ # Windows and Unix path styles.
+ file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace
+ [file, line.to_i]
+ end
+
def expand_backtrace
@exception.backtrace.unshift(
@exception.to_s.split("\n")
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index e90f8b9ce6..59639a010e 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -79,22 +79,31 @@ module ActionDispatch
class FlashHash
include Enumerable
- def self.from_session_value(value)
- flash = case value
- when FlashHash # Rails 3.1, 3.2
- new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
- when Hash # Rails 4.0
- new(value['flashes'], value['discard'])
- else
- new
- end
-
- flash.tap(&:sweep)
+ def self.from_session_value(value) #:nodoc:
+ case value
+ when FlashHash # Rails 3.1, 3.2
+ flashes = value.instance_variable_get(:@flashes)
+ if discard = value.instance_variable_get(:@used)
+ flashes.except!(*discard)
+ end
+ new(flashes, flashes.keys)
+ when Hash # Rails 4.0
+ flashes = value['flashes']
+ if discard = value['discard']
+ flashes.except!(*discard)
+ end
+ new(flashes, flashes.keys)
+ else
+ new
+ end
end
- def to_session_value
- return nil if empty?
- {'discard' => @discard.to_a, 'flashes' => @flashes}
+ # Builds a hash containing the flashes to keep for the next request.
+ # If there are none to keep, returns nil.
+ def to_session_value #:nodoc:
+ flashes_to_keep = @flashes.except(*@discard)
+ return nil if flashes_to_keep.empty?
+ {'flashes' => flashes_to_keep}
end
def initialize(flashes = {}, discard = []) #:nodoc:
@@ -132,7 +141,7 @@ module ActionDispatch
end
def key?(name)
- @flashes.key? name
+ @flashes.key? name.to_s
end
def delete(key)
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index b426183488..29d43faeed 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -47,7 +47,7 @@ module ActionDispatch
else
false
end
- rescue Exception => e # JSON or Ruby code block errors
+ rescue => e # JSON or Ruby code block errors
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
raise ParseError.new(e.message, e)
diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb
index 25658bac3d..cf31815c23 100644
--- a/actionpack/lib/action_dispatch/middleware/request_id.rb
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -12,19 +12,23 @@ module ActionDispatch
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
# from multiple pieces of the stack.
class RequestId
+ X_REQUEST_ID = "X-Request-Id".freeze # :nodoc:
+ ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc:
+ HTTP_X_REQUEST_ID = "HTTP_X_REQUEST_ID".freeze # :nodoc:
+
def initialize(app)
@app = app
end
def call(env)
- env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
- @app.call(env).tap { |_status, headers, _body| headers["X-Request-Id"] = env["action_dispatch.request_id"] }
+ env[ACTION_DISPATCH_REQUEST_ID] = external_request_id(env) || internal_request_id
+ @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = env[ACTION_DISPATCH_REQUEST_ID] }
end
private
def external_request_id(env)
- if request_id = env["HTTP_X_REQUEST_ID"].presence
- request_id.gsub(/[^\w\-]/, "").first(255)
+ if request_id = env[HTTP_X_REQUEST_ID].presence
+ request_id.gsub(/[^\w\-]/, "".freeze).first(255)
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index e66c21ef85..2e1bd45c3d 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -23,10 +23,19 @@ module ActionDispatch
def match?(path)
path = URI.parser.unescape(path)
return false unless path.valid_encoding?
+ path = Rack::Utils.clean_path_info path
paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"]
- if match = paths.detect {|p| File.file?(File.join(@root, p)) }
+ if match = paths.detect { |p|
+ path = File.join(@root, p)
+ begin
+ File.file?(path) && File.readable?(path)
+ rescue SystemCallError
+ false
+ end
+
+ }
return ::Rack::Utils.escape(match)
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
index db219c8fa9..49b1e83551 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
@@ -5,20 +5,8 @@
<pre id="blame_trace" <%='style="display:none"' if hide %>><code><%= @exception.describe_blame %></code></pre>
<% end %>
-<%
- clean_params = @request.filtered_parameters.clone
- clean_params.delete("action")
- clean_params.delete("controller")
-
- request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n")
-
- def debug_hash(object)
- object.to_hash.sort_by { |k, _| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n")
- end unless self.class.method_defined?(:debug_hash)
-%>
-
<h2 style="margin-top: 30px">Request</h2>
-<p><b>Parameters</b>:</p> <pre><%= request_dump %></pre>
+<p><b>Parameters</b>:</p> <pre><%= debug_params(@request.filtered_parameters) %></pre>
<div class="details">
<div class="summary"><a href="#" onclick="return toggleSessionDump()">Toggle session dump</a></div>
@@ -31,4 +19,4 @@
</div>
<h2 style="margin-top: 30px">Response</h2>
-<p><b>Headers</b>:</p> <pre><%= defined?(@response) ? @response.headers.inspect.gsub(',', ",\n") : 'None' %></pre>
+<p><b>Headers</b>:</p> <pre><%= debug_headers(defined?(@response) ? @response.headers : {}) %></pre>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
index ba29e26930..e7b913bbe4 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
@@ -1,29 +1,27 @@
-<% if @source_extract %>
- <% @source_extract.each_with_index do |extract_source, index| %>
- <% if extract_source[:code] %>
- <div class="source <%="hidden" if index != 0%>" id="frame-source-<%=index%>">
- <div class="info">
- Extracted source (around line <strong>#<%= extract_source[:line_number] %></strong>):
- </div>
- <div class="data">
- <table cellpadding="0" cellspacing="0" class="lines">
- <tr>
- <td>
- <pre class="line_numbers">
- <% extract_source[:code].each_key do |line_number| %>
+<% @source_extracts.each_with_index do |source_extract, index| %>
+ <% if source_extract[:code] %>
+ <div class="source <%="hidden" if @show_source_idx != index%>" id="frame-source-<%=index%>">
+ <div class="info">
+ Extracted source (around line <strong>#<%= source_extract[:line_number] %></strong>):
+ </div>
+ <div class="data">
+ <table cellpadding="0" cellspacing="0" class="lines">
+ <tr>
+ <td>
+ <pre class="line_numbers">
+ <% source_extract[:code].each_key do |line_number| %>
<span><%= line_number -%></span>
- <% end %>
- </pre>
- </td>
+ <% end %>
+ </pre>
+ </td>
<td width="100%">
<pre>
-<% extract_source[:code].each do |line, source| -%><div class="line<%= " active" if line == extract_source[:line_number] -%>"><%= source -%></div><% end -%>
+<% source_extract[:code].each do |line, source| -%><div class="line<%= " active" if line == source_extract[:line_number] -%>"><%= source -%></div><% end -%>
</pre>
</td>
- </tr>
- </table>
- </div>
+ </tr>
+ </table>
</div>
- <% end %>
+ </div>
<% end %>
<% end %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
index f62caf51d7..ab57b11c7d 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
@@ -12,7 +12,7 @@
<% end %>
<% @traces.each do |name, trace| %>
- <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == "Application Trace") ? 'block' : 'none' %>;">
+ <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == @trace_to_show) ? 'block' : 'none' %>;">
<pre><code><% trace.each do |frame| %><a class="trace-frames" data-frame-id="<%= frame[:id] %>" href="#"><%= frame[:trace] %></a><br><% end %></code></pre>
</div>
<% end %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
index 5c016e544e..2a65fd06ad 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
@@ -4,4 +4,8 @@
<div id="container">
<h2><%= h @exception.message %></h2>
+
+ <%= render template: "rescues/_source" %>
+ <%= render template: "rescues/_trace" %>
+ <%= render template: "rescues/_request_and_response" %>
</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
index 7e9cedb95e..55dd5ddc7b 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
@@ -27,4 +27,6 @@
<%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %>
<% end %>
+
+ <%= render template: "rescues/_request_and_response" %>
</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
index 6ffa242da4..5cee0b5932 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
@@ -1,6 +1,6 @@
<% content_for :style do %>
#route_table {
- margin: 0 auto 0;
+ margin: 0;
border-collapse: collapse;
}
diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb
index 9d4f1aa3c5..1c9371d89c 100644
--- a/actionpack/lib/action_dispatch/request/utils.rb
+++ b/actionpack/lib/action_dispatch/request/utils.rb
@@ -16,10 +16,6 @@ module ActionDispatch
when Array
v.grep(Hash) { |x| deep_munge(x, keys) }
v.compact!
- if v.empty?
- hash[k] = nil
- ActiveSupport::Notifications.instrument("deep_munge.action_controller", keys: keys)
- end
when Hash
deep_munge(v, keys)
end
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index ea3b2f419d..df5ebb6751 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -48,7 +48,7 @@ module ActionDispatch
def reqs
@reqs ||= begin
reqs = endpoint
- reqs += " #{constraints.to_s}" unless constraints.empty?
+ reqs += " #{constraints}" unless constraints.empty?
reqs
end
end
@@ -114,9 +114,7 @@ module ActionDispatch
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
- end.reject do |route|
- route.internal?
- end.collect do |route|
+ end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
{ name: route.name,
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index fc28740828..f2c9e7b1a0 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -7,7 +7,6 @@ require 'active_support/core_ext/module/remove_method'
require 'active_support/inflector'
require 'action_dispatch/routing/redirection'
require 'action_dispatch/routing/endpoint'
-require 'active_support/deprecation'
module ActionDispatch
module Routing
@@ -243,12 +242,10 @@ module ActionDispatch
def app(blocks)
if to.respond_to?(:call)
Constraints.new(to, blocks, false)
+ elsif blocks.any?
+ Constraints.new(dispatcher(defaults), blocks, true)
else
- if blocks.any?
- Constraints.new(dispatcher(defaults), blocks, true)
- else
- dispatcher(defaults)
- end
+ dispatcher(defaults)
end
end
@@ -280,14 +277,8 @@ module ActionDispatch
end
def split_to(to)
- case to
- when Symbol
- ActiveSupport::Deprecation.warn "defining a route where `to` is a symbol is deprecated. Please change \"to: :#{to}\" to \"action: :#{to}\""
- [nil, to.to_s]
- when /#/ then to.split('#')
- when String
- ActiveSupport::Deprecation.warn "defining a route where `to` is a controller without an action is deprecated. Please change \"to: :#{to}\" to \"controller: :#{to}\""
- [to, nil]
+ if to =~ /#/
+ to.split('#')
else
[]
end
@@ -382,7 +373,7 @@ module ActionDispatch
# Matches a url pattern to one or more routes.
#
- # You should not use the `match` method in your router
+ # You should not use the +match+ method in your router
# without specifying an HTTP method.
#
# If you want to expose your action to both GET and POST, use:
@@ -393,7 +384,7 @@ module ActionDispatch
# Note that +:controller+, +:action+ and +:id+ are interpreted as url
# query parameters and thus available through +params+ in an action.
#
- # If you want to expose your action to GET, use `get` in the router:
+ # If you want to expose your action to GET, use +get+ in the router:
#
# Instead of:
#
@@ -434,7 +425,7 @@ module ActionDispatch
#
# Because requesting various HTTP verbs with a single action has security
# implications, you must either specify the actions in
- # the via options or use one of the HtttpHelpers[rdoc-ref:HttpHelpers]
+ # the via options or use one of the HttpHelpers[rdoc-ref:HttpHelpers]
# instead +match+
#
# === Options
@@ -448,7 +439,7 @@ module ActionDispatch
# The route's action.
#
# [:param]
- # Overrides the default resource identifier `:id` (name of the
+ # Overrides the default resource identifier +:id+ (name of the
# dynamic segment used to generate the routes).
# You can access that segment from your controller using
# <tt>params[<:param>]</tt>.
@@ -573,13 +564,7 @@ module ActionDispatch
raise "A rack application must be specified" unless path
rails_app = rails_app? app
-
- if rails_app
- options[:as] ||= app.railtie_name
- else
- # non rails apps can't have an :as
- options[:as] = nil
- end
+ options[:as] ||= app_name(app, rails_app)
target_as = name_for_action(options[:as], path)
options[:via] ||= :all
@@ -611,6 +596,15 @@ module ActionDispatch
app.is_a?(Class) && app < Rails::Railtie
end
+ def app_name(app, rails_app)
+ if rails_app
+ app.railtie_name
+ elsif app.is_a?(Class)
+ class_name = app.name
+ ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
+ end
+ end
+
def define_generate_prefix(app, name)
_route = @set.named_routes.get name
_routes = @set
@@ -1745,9 +1739,10 @@ module ActionDispatch
member_name = parent_resource.member_name
end
- name = @scope.action_name(name_prefix, prefix, collection_name, member_name)
+ action_name = @scope.action_name(name_prefix, prefix, collection_name, member_name)
+ candidate = action_name.select(&:present?).join('_')
- if candidate = name.compact.join("_").presence
+ unless candidate.empty?
# If a name was not explicitly given, we check if it is valid
# and return nil in case it isn't. Otherwise, we pass the invalid name
# forward so the underlying router engine treats it and raises an exception.
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 0847842fa2..2e116ea9cd 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -1,5 +1,3 @@
-require 'action_controller/model_naming'
-
module ActionDispatch
module Routing
# Polymorphic URL helpers are methods for smart resolution to a named route call when
@@ -55,8 +53,6 @@ module ActionDispatch
# form_for([blog, @post]) # => "/blog/posts/1"
#
module PolymorphicRoutes
- include ActionController::ModelNaming
-
# Constructs a call to a named RESTful route for the given record and returns the
# resulting URL string. For example:
#
@@ -251,7 +247,7 @@ module ActionDispatch
args = []
model = record.to_model
- name = if record.persisted?
+ name = if model.persisted?
args << model
model.model_name.singular_route_key
else
@@ -294,11 +290,12 @@ module ActionDispatch
when Class
@key_strategy.call record.model_name
else
- if record.persisted?
- args << record.to_model
- record.to_model.model_name.singular_route_key
+ model = record.to_model
+ if model.persisted?
+ args << model
+ model.model_name.singular_route_key
else
- @key_strategy.call record.to_model.model_name
+ @key_strategy.call model.model_name
end
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index f51bee3b31..ce04f0b08a 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -12,14 +12,15 @@ require 'action_dispatch/routing/endpoint'
module ActionDispatch
module Routing
- class RouteSet #:nodoc:
+ # :stopdoc:
+ class RouteSet
# Since the router holds references to many parts of the system
# like engines, controllers and the application itself, inspecting
# the route set can actually be really slow, therefore we default
# alias inspect to to_s.
alias inspect to_s
- class Dispatcher < Routing::Endpoint #:nodoc:
+ class Dispatcher < Routing::Endpoint
def initialize(defaults)
@defaults = defaults
@controller_class_names = ThreadSafe::Cache.new
@@ -84,9 +85,9 @@ module ActionDispatch
# A NamedRouteCollection instance is a collection of named routes, and also
# maintains an anonymous module that can be used to install helpers for the
# named routes.
- class NamedRouteCollection #:nodoc:
+ class NamedRouteCollection
include Enumerable
- attr_reader :routes, :url_helpers_module
+ attr_reader :routes, :url_helpers_module, :path_helpers_module
def initialize
@routes = {}
@@ -101,11 +102,6 @@ module ActionDispatch
@path_helpers.include?(key) || @url_helpers.include?(key)
end
- def helpers
- ActiveSupport::Deprecation.warn("`named_routes.helpers` is deprecated, please use `route_defined?(route_name)` to see if a named route was defined.")
- @path_helpers + @url_helpers
- end
-
def helper_names
@path_helpers.map(&:to_s) + @url_helpers.map(&:to_s)
end
@@ -135,7 +131,7 @@ module ActionDispatch
end
routes[key] = route
define_url_helper @path_helpers_module, route, path_name, route.defaults, name, PATH
- define_url_helper @url_helpers_module, route, url_name, route.defaults, name, FULL
+ define_url_helper @url_helpers_module, route, url_name, route.defaults, name, UNKNOWN
@path_helpers << path_name
@url_helpers << url_name
@@ -166,26 +162,7 @@ module ActionDispatch
routes.length
end
- def path_helpers_module(warn = false)
- if warn
- mod = @path_helpers_module
- helpers = @path_helpers
- Module.new do
- include mod
-
- helpers.each do |meth|
- define_method(meth) do |*args, &block|
- ActiveSupport::Deprecation.warn("The method `#{meth}` cannot be used here as a full URL is required. Use `#{meth.to_s.sub(/_path$/, '_url')}` instead")
- super(*args, &block)
- end
- end
- end
- else
- @path_helpers_module
- end
- end
-
- class UrlHelper # :nodoc:
+ class UrlHelper
def self.create(route, options, route_name, url_strategy)
if optimize_helper?(route)
OptimizedUrlHelper.new(route, options, route_name, url_strategy)
@@ -200,7 +177,7 @@ module ActionDispatch
attr_reader :url_strategy, :route_name
- class OptimizedUrlHelper < UrlHelper # :nodoc:
+ class OptimizedUrlHelper < UrlHelper
attr_reader :arg_size
def initialize(route, options, route_name, url_strategy)
@@ -276,15 +253,22 @@ module ActionDispatch
end
def handle_positional_args(controller_options, inner_options, args, result, path_params)
-
if args.size > 0
- if args.size < path_params.size - 1 # take format into account
+ # take format into account
+ if path_params.include?(:format)
+ path_params_size = path_params.size - 1
+ else
+ path_params_size = path_params.size
+ end
+
+ if args.size < path_params_size
path_params -= controller_options.keys
path_params -= result.keys
end
- path_params.each { |param|
- result[param] = inner_options[param] || args.shift
- }
+ path_params -= inner_options.keys
+ path_params.take(args.size).each do |param|
+ result[param] = args.shift
+ end
end
result.merge!(inner_options)
@@ -317,12 +301,9 @@ module ActionDispatch
end
end
- # :stopdoc:
# strategy for building urls to send to the client
PATH = ->(options) { ActionDispatch::Http::URL.path_for(options) }
- FULL = ->(options) { ActionDispatch::Http::URL.full_url_for(options) }
UNKNOWN = ->(options) { ActionDispatch::Http::URL.url_for(options) }
- # :startdoc:
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
@@ -397,7 +378,7 @@ module ActionDispatch
Routing::RouteSet::Dispatcher.new(defaults)
end
- module MountedHelpers #:nodoc:
+ module MountedHelpers
extend ActiveSupport::Concern
include UrlFor
end
@@ -414,9 +395,11 @@ module ActionDispatch
return if MountedHelpers.method_defined?(name)
routes = self
+ helpers = routes.url_helpers
+
MountedHelpers.class_eval do
define_method "_#{name}" do
- RoutesProxy.new(routes, _routes_context)
+ RoutesProxy.new(routes, _routes_context, helpers)
end
end
@@ -427,7 +410,7 @@ module ActionDispatch
RUBY
end
- def url_helpers(include_path_helpers = true)
+ def url_helpers(supports_path = true)
routes = self
Module.new do
@@ -438,7 +421,14 @@ module ActionDispatch
# Rails.application.routes.url_helpers.url_for(args)
@_routes = routes
class << self
- delegate :url_for, :optimize_routes_generation?, to: '@_routes'
+ def url_for(options)
+ @_routes.url_for(options)
+ end
+
+ def optimize_routes_generation?
+ @_routes.optimize_routes_generation?
+ end
+
attr_reader :_routes
def url_options; {}; end
end
@@ -454,14 +444,12 @@ module ActionDispatch
# named routes...
include url_helpers
- if include_path_helpers
+ if supports_path
path_helpers = routes.named_routes.path_helpers_module
- else
- path_helpers = routes.named_routes.path_helpers_module(true)
- end
- include path_helpers
- extend path_helpers
+ include path_helpers
+ extend path_helpers
+ end
# plus a singleton class method called _routes ...
included do
@@ -472,6 +460,12 @@ module ActionDispatch
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
+
+ define_method(:_generate_paths_by_default) do
+ supports_path
+ end
+
+ private :_generate_paths_by_default
end
end
@@ -493,7 +487,7 @@ module ActionDispatch
path = conditions.delete :path_info
ast = conditions.delete :parsed_path_info
path = build_path(path, ast, requirements, anchor)
- conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
+ conditions = build_conditions(conditions, path.names.map(&:to_sym))
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
@@ -550,12 +544,12 @@ module ActionDispatch
end
private :build_conditions
- class Generator #:nodoc:
+ class Generator
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
- value.map { |v| v.to_param }.join('/')
+ value.map(&:to_param).join('/')
elsif param = value.to_param
param
end
@@ -699,10 +693,10 @@ module ActionDispatch
end
def find_script_name(options)
- options.delete(:script_name) { '' }
+ options.delete(:script_name) || ''
end
- def path_for(options, route_name = nil) # :nodoc:
+ def path_for(options, route_name = nil)
url_for(options, route_name, PATH)
end
@@ -788,5 +782,6 @@ module ActionDispatch
raise ActionController::RoutingError, "No route matches #{path.inspect}"
end
end
+ # :startdoc:
end
end
diff --git a/actionpack/lib/action_dispatch/routing/routes_proxy.rb b/actionpack/lib/action_dispatch/routing/routes_proxy.rb
index e2393d3799..040ea04046 100644
--- a/actionpack/lib/action_dispatch/routing/routes_proxy.rb
+++ b/actionpack/lib/action_dispatch/routing/routes_proxy.rb
@@ -8,8 +8,9 @@ module ActionDispatch
attr_accessor :scope, :routes
alias :_routes :routes
- def initialize(routes, scope)
+ def initialize(routes, scope, helpers)
@routes, @scope = routes, scope
+ @helpers = helpers
end
def url_options
@@ -19,16 +20,16 @@ module ActionDispatch
end
def respond_to?(method, include_private = false)
- super || routes.url_helpers.respond_to?(method)
+ super || @helpers.respond_to?(method)
end
def method_missing(method, *args)
- if routes.url_helpers.respond_to?(method)
+ if @helpers.respond_to?(method)
self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{method}(*args)
options = args.extract_options!
args << url_options.merge((options || {}).symbolize_keys)
- routes.url_helpers.#{method}(*args)
+ @helpers.#{method}(*args)
end
RUBY
send(method, *args)
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index eb554ec383..dca86858cc 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -184,6 +184,12 @@ module ActionDispatch
def _routes_context
self
end
+
+ private
+
+ def _generate_paths_by_default
+ true
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
index 41d00b5e2b..f325c35b57 100644
--- a/actionpack/lib/action_dispatch/testing/assertions.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -15,7 +15,7 @@ module ActionDispatch
@html_document ||= if @response.content_type =~ /xml$/
Nokogiri::XML::Document.parse(@response.body)
else
- Nokogiri::HTML::DocumentFragment.parse(@response.body)
+ Nokogiri::HTML::Document.parse(@response.body)
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
deleted file mode 100644
index fb579b52fe..0000000000
--- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("ActionDispatch::Assertions::DomAssertions has been extracted to the rails-dom-testing gem.") \ No newline at end of file
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index e06f7037c6..a927738b42 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -144,13 +144,7 @@ module ActionDispatch
old_controller, @controller = @controller, @controller.clone
_routes = @routes
- # Unfortunately, there is currently an abstraction leak between AC::Base
- # and AV::Base which requires having the URL helpers in both AC and AV.
- # To do this safely at runtime for tests, we need to bump up the helper serial
- # to that the old AV subclass isn't cached.
- #
- # TODO: Make this unnecessary
- @controller.singleton_class.send(:include, _routes.url_helpers)
+ @controller.singleton_class.include(_routes.url_helpers)
@controller.view_context_class = Class.new(@controller.view_context_class) do
include _routes.url_helpers
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
deleted file mode 100644
index 7361e6c44b..0000000000
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("ActionDispatch::Assertions::SelectorAssertions has been extracted to the rails-dom-testing gem.")
diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb
deleted file mode 100644
index 5c2905d1ac..0000000000
--- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-require 'active_support/deprecation'
-
-ActiveSupport::Deprecation.warn("ActionDispatch::Assertions::TagAssertions has been extracted to the rails-dom-testing gem.")
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index c300a4ea0d..9b00616968 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -12,12 +12,14 @@ module ActionDispatch
#
# - +path+: The URI (as a String) on which you want to perform a GET
# request.
- # - +parameters+: The HTTP parameters that you want to pass. This may
+ # - +params+: The HTTP parameters that you want to pass. This may
# be +nil+,
# a Hash, or a String that is appropriately encoded
# (<tt>application/x-www-form-urlencoded</tt> or
# <tt>multipart/form-data</tt>).
- # - +headers_or_env+: Additional headers to pass, as a Hash. The headers will be
+ # - +headers+: Additional headers to pass, as a Hash. The headers will be
+ # merged into the Rack env hash.
+ # - +env+: Additional env to pass, as a Hash. The headers will be
# merged into the Rack env hash.
#
# This method returns a Response object, which one can use to
@@ -28,38 +30,43 @@ module ActionDispatch
#
# You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
# +#post+, +#patch+, +#put+, +#delete+, and +#head+.
- def get(path, parameters = nil, headers_or_env = nil)
- process :get, path, parameters, headers_or_env
+ #
+ # Example:
+ #
+ # get '/feed', params: { since: 201501011400 }
+ # post '/profile', headers: { "X-Test-Header" => "testvalue" }
+ def get(path, *args)
+ process_with_kwargs(:get, path, *args)
end
# Performs a POST request with the given parameters. See +#get+ for more
# details.
- def post(path, parameters = nil, headers_or_env = nil)
- process :post, path, parameters, headers_or_env
+ def post(path, *args)
+ process_with_kwargs(:post, path, *args)
end
# Performs a PATCH request with the given parameters. See +#get+ for more
# details.
- def patch(path, parameters = nil, headers_or_env = nil)
- process :patch, path, parameters, headers_or_env
+ def patch(path, *args)
+ process_with_kwargs(:patch, path, *args)
end
# Performs a PUT request with the given parameters. See +#get+ for more
# details.
- def put(path, parameters = nil, headers_or_env = nil)
- process :put, path, parameters, headers_or_env
+ def put(path, *args)
+ process_with_kwargs(:put, path, *args)
end
# Performs a DELETE request with the given parameters. See +#get+ for
# more details.
- def delete(path, parameters = nil, headers_or_env = nil)
- process :delete, path, parameters, headers_or_env
+ def delete(path, *args)
+ process_with_kwargs(:delete, path, *args)
end
# Performs a HEAD request with the given parameters. See +#get+ for more
# details.
- def head(path, parameters = nil, headers_or_env = nil)
- process :head, path, parameters, headers_or_env
+ def head(path, *args)
+ process_with_kwargs(:head, path, *args)
end
# Performs an XMLHttpRequest request with the given parameters, mirroring
@@ -68,11 +75,29 @@ module ActionDispatch
# The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
# +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
# string; the headers are a hash.
- def xml_http_request(request_method, path, parameters = nil, headers_or_env = nil)
- headers_or_env ||= {}
- headers_or_env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
- headers_or_env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
- process(request_method, path, parameters, headers_or_env)
+ #
+ # Example:
+ #
+ # xhr :get, '/feed', params: { since: 201501011400 }
+ def xml_http_request(request_method, path, *args)
+ if kwarg_request?(*args)
+ params, headers, env = args.first.values_at(:params, :headers, :env)
+ else
+ params = args[0]
+ headers = args[1]
+ env = {}
+
+ if params.present? || headers.present?
+ non_kwarg_request_warning
+ end
+ end
+
+ ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
+ xhr and xml_http_request methods are deprecated in favor of
+ `get "/posts", xhr: true` and `post "/posts/1", xhr: true`
+ MSG
+
+ process(request_method, path, params: params, headers: headers, xhr: true)
end
alias xhr :xml_http_request
@@ -89,40 +114,52 @@ module ActionDispatch
# redirect. Note that the redirects are followed until the response is
# not a redirect--this means you may run into an infinite loop if your
# redirect loops back to itself.
- def request_via_redirect(http_method, path, parameters = nil, headers_or_env = nil)
- process(http_method, path, parameters, headers_or_env)
+ #
+ # Example:
+ #
+ # request_via_redirect :post, '/welcome',
+ # params: { ref_id: 14 },
+ # headers: { "X-Test-Header" => "testvalue" }
+ def request_via_redirect(http_method, path, *args)
+ process_with_kwargs(http_method, path, *args)
+
follow_redirect! while redirect?
status
end
# Performs a GET request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
- def get_via_redirect(path, parameters = nil, headers_or_env = nil)
- request_via_redirect(:get, path, parameters, headers_or_env)
+ def get_via_redirect(path, *args)
+ ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ request_via_redirect(:get, path, *args)
end
# Performs a POST request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
- def post_via_redirect(path, parameters = nil, headers_or_env = nil)
- request_via_redirect(:post, path, parameters, headers_or_env)
+ def post_via_redirect(path, *args)
+ ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ request_via_redirect(:post, path, *args)
end
# Performs a PATCH request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
- def patch_via_redirect(path, parameters = nil, headers_or_env = nil)
- request_via_redirect(:patch, path, parameters, headers_or_env)
+ def patch_via_redirect(path, *args)
+ ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ request_via_redirect(:patch, path, *args)
end
# Performs a PUT request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
- def put_via_redirect(path, parameters = nil, headers_or_env = nil)
- request_via_redirect(:put, path, parameters, headers_or_env)
+ def put_via_redirect(path, *args)
+ ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ request_via_redirect(:put, path, *args)
end
# Performs a DELETE request, following any subsequent redirect.
# See +request_via_redirect+ for more information.
- def delete_via_redirect(path, parameters = nil, headers_or_env = nil)
- request_via_redirect(:delete, path, parameters, headers_or_env)
+ def delete_via_redirect(path, *args)
+ ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in the next version of Rails. Please use follow_redirect! manually after the request call for the same behavior.')
+ request_via_redirect(:delete, path, *args)
end
end
@@ -185,15 +222,6 @@ module ActionDispatch
super()
@app = app
- # If the app is a Rails app, make url_helpers available on the session
- # This makes app.url_for and app.foo_path available in the console
- if app.respond_to?(:routes)
- singleton_class.class_eval do
- include app.routes.url_helpers
- include app.routes.mounted_helpers
- end
- end
-
reset!
end
@@ -261,8 +289,38 @@ module ActionDispatch
@_mock_session ||= Rack::MockSession.new(@app, host)
end
+ def process_with_kwargs(http_method, path, *args)
+ if kwarg_request?(*args)
+ process(http_method, path, *args)
+ else
+ non_kwarg_request_warning if args.present?
+ process(http_method, path, { params: args[0], headers: args[1] })
+ end
+ end
+
+ REQUEST_KWARGS = %i(params headers env xhr)
+ def kwarg_request?(*args)
+ args[0].respond_to?(:keys) && args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
+ end
+
+ def non_kwarg_request_warning
+ ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
+ ActionDispatch::IntegrationTest HTTP request methods will accept only
+ the following keyword arguments in future Rails versions:
+ #{REQUEST_KWARGS.join(', ')}
+
+ Examples:
+
+ get '/profile',
+ params: { id: 1 },
+ headers: { 'X-Extra-Header' => '123' },
+ env: { 'action_dispatch.custom' => 'custom' },
+ xhr: true
+ MSG
+ end
+
# Performs the actual request.
- def process(method, path, parameters = nil, headers_or_env = nil)
+ def process(method, path, params: nil, headers: nil, env: nil, xhr: false)
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
@@ -272,9 +330,9 @@ module ActionDispatch
hostname, port = host.split(':')
- env = {
+ request_env = {
:method => method,
- :params => parameters,
+ :params => params,
"SERVER_NAME" => hostname,
"SERVER_PORT" => port || (https? ? "443" : "80"),
@@ -287,14 +345,26 @@ module ActionDispatch
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
"HTTP_ACCEPT" => accept
}
- # this modifies the passed env directly
- Http::Headers.new(env).merge!(headers_or_env || {})
+
+ if xhr
+ headers ||= {}
+ headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
+ headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
+ end
+
+ # this modifies the passed request_env directly
+ if headers.present?
+ Http::Headers.new(request_env).merge!(headers)
+ end
+ if env.present?
+ Http::Headers.new(request_env).merge!(env)
+ end
session = Rack::Test::Session.new(_mock_session)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
# Make sure requested path is always a full uri
- session.request(build_full_uri(path, env), env)
+ session.request(build_full_uri(path, request_env), request_env)
@request_count += 1
@request = ActionDispatch::Request.new(session.last_request.env)
@@ -305,7 +375,7 @@ module ActionDispatch
@controller = session.last_request.env['action_controller.instance']
- return response.status
+ response.status
end
def build_full_uri(path, env)
@@ -316,23 +386,51 @@ module ActionDispatch
module Runner
include ActionDispatch::Assertions
- def app
- @app ||= nil
+ APP_SESSIONS = {}
+
+ attr_reader :app
+
+ def before_setup
+ super
+ @app = nil
+ @integration_session = nil
+ end
+
+ def integration_session
+ @integration_session ||= create_session(app)
end
# Reset the current session. This is useful for testing multiple sessions
# in a single test case.
def reset!
- @integration_session = Integration::Session.new(app)
+ @integration_session = create_session(app)
+ end
+
+ def create_session(app)
+ klass = APP_SESSIONS[app] ||= Class.new(Integration::Session) {
+ # If the app is a Rails app, make url_helpers available on the session
+ # This makes app.url_for and app.foo_path available in the console
+ if app.respond_to?(:routes)
+ include app.routes.url_helpers
+ include app.routes.mounted_helpers
+ end
+ }
+ klass.new(app)
+ end
+
+ def remove! # :nodoc:
+ @integration_session = nil
end
%w(get post patch put head delete cookies assigns
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
define_method(method) do |*args|
- reset! unless integration_session
- reset_template_assertion
- # reset the html_document variable, but only for new get/post calls
- @html_document = nil unless method == 'cookies' || method == 'assigns'
+ # reset the html_document variable, except for cookies/assigns calls
+ unless method == 'cookies' || method == 'assigns'
+ @html_document = nil
+ reset_template_assertion
+ end
+
integration_session.__send__(method, *args).tap do
copy_session_variables!
end
@@ -358,19 +456,16 @@ module ActionDispatch
# Copy the instance variables from the current session instance into the
# test instance.
def copy_session_variables! #:nodoc:
- return unless integration_session
- %w(controller response request).each do |var|
- instance_variable_set("@#{var}", @integration_session.__send__(var))
- end
+ @controller = @integration_session.controller
+ @response = @integration_session.response
+ @request = @integration_session.request
end
def default_url_options
- reset! unless integration_session
integration_session.default_url_options
end
def default_url_options=(options)
- reset! unless integration_session
integration_session.default_url_options = options
end
@@ -380,7 +475,6 @@ module ActionDispatch
# Delegate unhandled messages to the current session instance.
def method_missing(sym, *args, &block)
- reset! unless integration_session
if integration_session.respond_to?(sym)
integration_session.__send__(sym, *args, &block).tap do
copy_session_variables!
@@ -389,11 +483,6 @@ module ActionDispatch
super
end
end
-
- private
- def integration_session
- @integration_session ||= nil
- end
end
end
@@ -472,6 +561,84 @@ module ActionDispatch
# end
# end
# end
+ #
+ # Another longer example would be:
+ #
+ # A simple integration test that exercises multiple controllers:
+ #
+ # require 'test_helper'
+ #
+ # class UserFlowsTest < ActionDispatch::IntegrationTest
+ # test "login and browse site" do
+ # # login via https
+ # https!
+ # get "/login"
+ # assert_response :success
+ #
+ # post_via_redirect "/login", username: users(:david).username, password: users(:david).password
+ # assert_equal '/welcome', path
+ # assert_equal 'Welcome david!', flash[:notice]
+ #
+ # https!(false)
+ # get "/articles/all"
+ # assert_response :success
+ # assert assigns(:articles)
+ # end
+ # end
+ #
+ # As you can see the integration test involves multiple controllers and
+ # exercises the entire stack from database to dispatcher. In addition you can
+ # have multiple session instances open simultaneously in a test and extend
+ # those instances with assertion methods to create a very powerful testing
+ # DSL (domain-specific language) just for your application.
+ #
+ # Here's an example of multiple sessions and custom DSL in an integration test
+ #
+ # require 'test_helper'
+ #
+ # class UserFlowsTest < ActionDispatch::IntegrationTest
+ # test "login and browse site" do
+ # # User david logs in
+ # david = login(:david)
+ # # User guest logs in
+ # guest = login(:guest)
+ #
+ # # Both are now available in different sessions
+ # assert_equal 'Welcome david!', david.flash[:notice]
+ # assert_equal 'Welcome guest!', guest.flash[:notice]
+ #
+ # # User david can browse site
+ # david.browses_site
+ # # User guest can browse site as well
+ # guest.browses_site
+ #
+ # # Continue with other assertions
+ # end
+ #
+ # private
+ #
+ # module CustomDsl
+ # def browses_site
+ # get "/products/all"
+ # assert_response :success
+ # assert assigns(:products)
+ # end
+ # end
+ #
+ # def login(user)
+ # open_session do |sess|
+ # sess.extend(CustomDsl)
+ # u = users(user)
+ # sess.https!
+ # sess.post "/login", username: u.username, password: u.password
+ # assert_equal '/welcome', sess.path
+ # sess.https!(false)
+ # end
+ # end
+ # end
+ #
+ # Consult the Rails Testing Guide for more.
+
class IntegrationTest < ActiveSupport::TestCase
include Integration::Runner
include ActionController::TemplateAssertions
@@ -492,12 +659,11 @@ module ActionDispatch
end
def url_options
- reset! unless integration_session
integration_session.url_options
end
def document_root_element
- html_document
+ html_document.root
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index de3dc5f924..4b9a088265 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -60,7 +60,7 @@ module ActionDispatch
def accept=(mime_types)
@env.delete('action_dispatch.request.accepts')
- @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
+ @env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",")
end
alias :rack_cookies :cookies
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
index 82039e72e7..369ea1467c 100644
--- a/actionpack/lib/action_dispatch/testing/test_response.rb
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -25,5 +25,12 @@ module ActionDispatch
# Was there a server-side error?
alias_method :error?, :server_error?
+
+ def merge_default_headers(original, *args)
+ # Default headers are already applied, no need to merge them a second time.
+ # This makes sure that default headers, removed in controller actions, will
+ # not be reapplied to the test response.
+ original
+ end
end
end
diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb
index 77f656d6f1..f664dab620 100644
--- a/actionpack/lib/action_pack.rb
+++ b/actionpack/lib/action_pack.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2014 David Heinemeier Hansson
+# Copyright (c) 2004-2015 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb
index 6834845d4f..255ac9f4ed 100644
--- a/actionpack/lib/action_pack/gem_version.rb
+++ b/actionpack/lib/action_pack/gem_version.rb
@@ -5,10 +5,10 @@ module ActionPack
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta2"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb
index 8cba049485..07571602e4 100644
--- a/actionpack/test/abstract/callbacks_test.rb
+++ b/actionpack/test/abstract/callbacks_test.rb
@@ -267,9 +267,11 @@ module AbstractController
end
class AliasedCallbacks < ControllerWithCallbacks
- before_filter :first
- after_filter :second
- around_filter :aroundz
+ ActiveSupport::Deprecation.silence do
+ before_filter :first
+ after_filter :second
+ around_filter :aroundz
+ end
def first
@text = "Hello world"
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
index 4fdc480b43..8289252dfc 100644
--- a/actionpack/test/abstract/translation_test.rb
+++ b/actionpack/test/abstract/translation_test.rb
@@ -9,6 +9,22 @@ module AbstractController
class TranslationControllerTest < ActiveSupport::TestCase
def setup
@controller = TranslationController.new
+ I18n.backend.store_translations(:en, {
+ one: {
+ two: 'bar',
+ },
+ abstract_controller: {
+ testing: {
+ translation: {
+ index: {
+ foo: 'bar',
+ },
+ no_action: 'no_action_tr',
+ },
+ },
+ },
+ })
+ @controller.stubs(action_name: :index)
end
def test_action_controller_base_responds_to_translate
@@ -28,16 +44,19 @@ module AbstractController
end
def test_lazy_lookup
- expected = 'bar'
- @controller.stubs(action_name: :index)
- I18n.stubs(:translate).with('abstract_controller.testing.translation.index.foo').returns(expected)
- assert_equal expected, @controller.t('.foo')
+ assert_equal 'bar', @controller.t('.foo')
+ end
+
+ def test_lazy_lookup_with_symbol
+ assert_equal 'bar', @controller.t(:'.foo')
+ end
+
+ def test_lazy_lookup_fallback
+ assert_equal 'no_action_tr', @controller.t(:'.no_action')
end
def test_default_translation
- key, expected = 'one.two', 'bar'
- I18n.stubs(:translate).with(key).returns(expected)
- assert_equal expected, @controller.t(key)
+ assert_equal 'bar', @controller.t('one.two')
end
def test_localize
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 69312e4c22..2d69ceed3a 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -21,6 +21,7 @@ PROCESS_COUNT = (ENV['N'] || 4).to_i
require 'active_support/testing/autorun'
require 'abstract_controller'
+require 'abstract_controller/railties/routes_helpers'
require 'action_controller'
require 'action_view'
require 'action_view/testing/resolvers'
@@ -53,7 +54,7 @@ I18n.enforce_available_locales = false
# Register danish language for testing
I18n.backend.store_translations 'da', {}
I18n.backend.store_translations 'pt-BR', {}
-ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
+ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
@@ -194,6 +195,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
yield temporary_routes
ensure
self.class.app = old_app
+ self.remove!
silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) }
end
@@ -259,7 +261,7 @@ end
module ActionController
class Base
# This stub emulates the Railtie including the URL helpers from a Rails application
- include SharedTestRoutes.url_helpers
+ extend AbstractController::Railties::RoutesHelpers.with(SharedTestRoutes)
include SharedTestRoutes.mounted_helpers
self.view_paths = FIXTURE_LOAD_PATH
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index f2a4503f13..21586e2193 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -378,7 +378,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
def test_render_based_on_parameters
- process :render_based_on_parameters, "GET", "name" => "David"
+ process :render_based_on_parameters,
+ method: "GET",
+ params: { name: "David" }
assert_equal "Mr. David", @response.body
end
@@ -575,6 +577,13 @@ class AssertTemplateTest < ActionController::TestCase
end
end
+ def test_fails_expecting_not_known_layout
+ get :render_with_layout
+ assert_raise(ArgumentError) do
+ assert_template :layout => 1
+ end
+ end
+
def test_passes_with_correct_layout
get :render_with_layout
assert_template :layout => "layouts/standard"
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index 950788743e..f7ad8e5158 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -1,31 +1,11 @@
require 'abstract_unit'
require 'active_support/logger'
require 'controller/fake_models'
-require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
# Provide some controller to run the tests on.
module Submodule
class ContainedEmptyController < ActionController::Base
end
-
- class ContainedNonEmptyController < ActionController::Base
- def public_action
- render :nothing => true
- end
-
- hide_action :hidden_action
- def hidden_action
- raise "Noooo!"
- end
-
- def another_hidden_action
- end
- hide_action :another_hidden_action
- end
-
- class SubclassedController < ContainedNonEmptyController
- hide_action :public_action # Hiding it here should not affect the superclass.
- end
end
class EmptyController < ActionController::Base
@@ -35,10 +15,6 @@ class NonEmptyController < ActionController::Base
def public_action
render :nothing => true
end
-
- hide_action :hidden_action
- def hidden_action
- end
end
class DefaultUrlOptionsController < ActionController::Base
@@ -51,6 +27,16 @@ class DefaultUrlOptionsController < ActionController::Base
end
end
+class OptionalDefaultUrlOptionsController < ActionController::Base
+ def show
+ render nothing: true
+ end
+
+ def default_url_options
+ { format: 'atom', id: 'default-id' }
+ end
+end
+
class UrlOptionsController < ActionController::Base
def from_view
render :inline => "<%= #{params[:route]} %>"
@@ -108,10 +94,7 @@ class ControllerInstanceTests < ActiveSupport::TestCase
def setup
@empty = EmptyController.new
@contained = Submodule::ContainedEmptyController.new
- @empty_controllers = [@empty, @contained, Submodule::SubclassedController.new]
-
- @non_empty_controllers = [NonEmptyController.new,
- Submodule::ContainedNonEmptyController.new]
+ @empty_controllers = [@empty, @contained]
end
def test_performed?
@@ -124,10 +107,6 @@ class ControllerInstanceTests < ActiveSupport::TestCase
@empty_controllers.each do |c|
assert_equal Set.new, c.class.action_methods, "#{c.controller_path} should be empty!"
end
-
- @non_empty_controllers.each do |c|
- assert_equal Set.new(%w(public_action)), c.class.action_methods, "#{c.controller_path} should not be empty!"
- end
end
def test_temporary_anonymous_controllers
@@ -161,12 +140,6 @@ class PerformActionTest < ActionController::TestCase
assert_equal "The action 'non_existent' could not be found for EmptyController", exception.message
end
- def test_get_on_hidden_should_fail
- use_controller NonEmptyController
- assert_raise(AbstractController::ActionNotFound) { get :hidden_action }
- assert_raise(AbstractController::ActionNotFound) { get :another_hidden_action }
- end
-
def test_action_missing_should_work
use_controller ActionMissingController
get :arbitrary_action
@@ -205,7 +178,7 @@ class UrlOptionsTest < ActionController::TestCase
get ':controller/:action'
end
- get :from_view, :route => "from_view_url"
+ get :from_view, params: { route: "from_view_url" }
assert_equal 'http://www.override.com/from_view', @response.body
assert_equal 'http://www.override.com/from_view', @controller.send(:from_view_url)
@@ -239,7 +212,7 @@ class DefaultUrlOptionsTest < ActionController::TestCase
get ':controller/:action'
end
- get :from_view, :route => "from_view_url"
+ get :from_view, params: { route: "from_view_url" }
assert_equal 'http://www.override.com/from_view?locale=en', @response.body
assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url)
@@ -256,7 +229,7 @@ class DefaultUrlOptionsTest < ActionController::TestCase
get ':controller/:action'
end
- get :from_view, :route => "description_path(1)"
+ get :from_view, params: { route: "description_path(1)" }
assert_equal '/en/descriptions/1', @response.body
assert_equal '/en/descriptions', @controller.send(:descriptions_path)
@@ -271,7 +244,18 @@ class DefaultUrlOptionsTest < ActionController::TestCase
assert_equal '/en/descriptions/1.xml', @controller.send(:description_path, 1, :format => "xml")
end
end
+end
+class OptionalDefaultUrlOptionsControllerTest < ActionController::TestCase
+ def test_default_url_options_override_missing_positional_arguments
+ with_routing do |set|
+ set.draw do
+ get "/things/:id(.:format)" => 'things#show', :as => :thing
+ end
+ assert_equal '/things/1.atom', thing_path('1')
+ assert_equal '/things/default-id.atom', thing_path
+ end
+ end
end
class EmptyUrlOptionsTest < ActionController::TestCase
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index c0e6a2ebd1..4760ec1698 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -210,7 +210,7 @@ CACHED
end
def test_skipping_fragment_cache_digesting
- get :fragment_cached_without_digest, :format => "html"
+ get :fragment_cached_without_digest, format: "html"
assert_response :success
expected_body = "<body>\n<p>ERB</p>\n</body>\n"
@@ -244,7 +244,7 @@ CACHED
end
def test_html_formatted_fragment_caching
- get :formatted_fragment_cached, :format => "html"
+ get :formatted_fragment_cached, format: "html"
assert_response :success
expected_body = "<body>\n<p>ERB</p>\n</body>\n"
@@ -255,7 +255,7 @@ CACHED
end
def test_xml_formatted_fragment_caching
- get :formatted_fragment_cached, :format => "xml"
+ get :formatted_fragment_cached, format: "xml"
assert_response :success
expected_body = "<body>\n <p>Builder</p>\n</body>\n"
@@ -269,7 +269,7 @@ CACHED
def test_fragment_caching_with_variant
@request.variant = :phone
- get :formatted_fragment_cached_with_variant, :format => "html"
+ get :formatted_fragment_cached_with_variant, format: "html"
assert_response :success
expected_body = "<body>\n<p>PHONE</p>\n</body>\n"
diff --git a/actionpack/test/controller/default_url_options_with_before_action_test.rb b/actionpack/test/controller/default_url_options_with_before_action_test.rb
index 656fd0431e..230f40d7ad 100644
--- a/actionpack/test/controller/default_url_options_with_before_action_test.rb
+++ b/actionpack/test/controller/default_url_options_with_before_action_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
-
class ControllerWithBeforeActionAndDefaultUrlOptions < ActionController::Base
before_action { I18n.locale = params[:locale] }
@@ -23,7 +22,7 @@ class ControllerWithBeforeActionAndDefaultUrlOptionsTest < ActionController::Tes
# This test has its roots in issue #1872
test "should redirect with correct locale :de" do
- get :redirect, :locale => "de"
+ get :redirect, params: { locale: "de" }
assert_redirected_to "/controller_with_before_action_and_default_url_options/target?locale=de"
end
end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index b2b01b3fa9..b9fb6be4e3 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -10,7 +10,7 @@ class ActionController::Base
def before_actions
filters = _process_action_callbacks.select { |c| c.kind == :before }
- filters.map! { |c| c.raw_filter }
+ filters.map!(&:raw_filter)
end
end
@@ -225,6 +225,30 @@ class FilterTest < ActionController::TestCase
skip_before_action :clean_up_tmp, if: -> { true }
end
+ class SkipFilterUsingOnlyAndIf < ConditionalFilterController
+ before_action :clean_up_tmp
+ before_action :ensure_login
+
+ skip_before_action :ensure_login, only: :login, if: -> { false }
+ skip_before_action :clean_up_tmp, only: :login, if: -> { true }
+
+ def login
+ render text: 'ok'
+ end
+ end
+
+ class SkipFilterUsingIfAndExcept < ConditionalFilterController
+ before_action :clean_up_tmp
+ before_action :ensure_login
+
+ skip_before_action :ensure_login, if: -> { false }, except: :login
+ skip_before_action :clean_up_tmp, if: -> { true }, except: :login
+
+ def login
+ render text: 'ok'
+ end
+ end
+
class ClassController < ConditionalFilterController
before_action ConditionalClassFilter
end
@@ -504,7 +528,6 @@ class FilterTest < ActionController::TestCase
def non_yielding_action
@filters << "it didn't yield"
- @filter_return_value
end
def action_three
@@ -528,32 +551,15 @@ class FilterTest < ActionController::TestCase
end
end
- def test_non_yielding_around_actions_not_returning_false_do_not_raise
+ def test_non_yielding_around_actions_do_not_raise
controller = NonYieldingAroundFilterController.new
- controller.instance_variable_set "@filter_return_value", true
assert_nothing_raised do
test_process(controller, "index")
end
end
- def test_non_yielding_around_actions_returning_false_do_not_raise
- controller = NonYieldingAroundFilterController.new
- controller.instance_variable_set "@filter_return_value", false
- assert_nothing_raised do
- test_process(controller, "index")
- end
- end
-
- def test_after_actions_are_not_run_if_around_action_returns_false
- controller = NonYieldingAroundFilterController.new
- controller.instance_variable_set "@filter_return_value", false
- test_process(controller, "index")
- assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters']
- end
-
def test_after_actions_are_not_run_if_around_action_does_not_yield
controller = NonYieldingAroundFilterController.new
- controller.instance_variable_set "@filter_return_value", true
test_process(controller, "index")
assert_equal ["filter_one", "it didn't yield"], controller.assigns['filters']
end
@@ -614,6 +620,16 @@ class FilterTest < ActionController::TestCase
assert_equal %w( ensure_login ), assigns["ran_filter"]
end
+ def test_if_is_ignored_when_used_with_only
+ test_process(SkipFilterUsingOnlyAndIf, 'login')
+ assert_nil assigns['ran_filter']
+ end
+
+ def test_except_is_ignored_when_used_with_if
+ test_process(SkipFilterUsingIfAndExcept, 'login')
+ assert_equal %w(ensure_login), assigns["ran_filter"]
+ end
+
def test_skipping_class_actions
test_process(ClassController)
assert_equal true, assigns["ran_class_action"]
@@ -1021,21 +1037,21 @@ class YieldingAroundFiltersTest < ActionController::TestCase
def test_first_action_in_multiple_before_action_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_1')
- assert_equal ' ', response.body
+ assert_equal '', response.body
assert_equal 1, controller.instance_variable_get(:@try)
end
def test_second_action_in_multiple_before_action_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_2')
- assert_equal ' ', response.body
+ assert_equal '', response.body
assert_equal 2, controller.instance_variable_get(:@try)
end
def test_last_action_in_multiple_before_action_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_3')
- assert_equal ' ', response.body
+ assert_equal '', response.body
assert_equal 3, controller.instance_variable_get(:@try)
end
diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb
index 50b36a0567..081288ef21 100644
--- a/actionpack/test/controller/flash_hash_test.rb
+++ b/actionpack/test/controller/flash_hash_test.rb
@@ -29,6 +29,15 @@ module ActionDispatch
assert_equal 'world', @hash['hello']
end
+ def test_key
+ @hash['foo'] = 'bar'
+
+ assert @hash.key?('foo')
+ assert @hash.key?(:foo)
+ assert_not @hash.key?('bar')
+ assert_not @hash.key?(:bar)
+ end
+
def test_delete
@hash['foo'] = 'bar'
@hash.delete 'foo'
@@ -48,33 +57,36 @@ module ActionDispatch
def test_to_session_value
@hash['foo'] = 'bar'
- assert_equal({'flashes' => {'foo' => 'bar'}, 'discard' => []}, @hash.to_session_value)
-
- @hash.discard('foo')
- assert_equal({'flashes' => {'foo' => 'bar'}, 'discard' => %w[foo]}, @hash.to_session_value)
+ assert_equal({'flashes' => {'foo' => 'bar'}}, @hash.to_session_value)
@hash.now['qux'] = 1
- assert_equal({'flashes' => {'foo' => 'bar', 'qux' => 1}, 'discard' => %w[foo qux]}, @hash.to_session_value)
+ assert_equal({'flashes' => {'foo' => 'bar'}}, @hash.to_session_value)
+
+ @hash.discard('foo')
+ assert_equal(nil, @hash.to_session_value)
@hash.sweep
assert_equal(nil, @hash.to_session_value)
end
def test_from_session_value
- rails_3_2_cookie = 'BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJWY4ZTFiODE1MmJhNzYwOWMyOGJiYjE3ZWM5MjYzYmE3BjsAVEkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsAOgxAY2xvc2VkRjoNQGZsYXNoZXN7BkkiDG1lc3NhZ2UGOwBGSSIKSGVsbG8GOwBGOglAbm93MA=='
+ # {"session_id"=>"f8e1b8152ba7609c28bbb17ec9263ba7", "flash"=>#<ActionDispatch::Flash::FlashHash:0x00000000000000 @used=#<Set: {"farewell"}>, @closed=false, @flashes={"greeting"=>"Hello", "farewell"=>"Goodbye"}, @now=nil>}
+ rails_3_2_cookie = 'BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJWY4ZTFiODE1MmJhNzYwOWMyOGJiYjE3ZWM5MjYzYmE3BjsAVEkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsGSSINZmFyZXdlbGwGOwBUVDoMQGNsb3NlZEY6DUBmbGFzaGVzewdJIg1ncmVldGluZwY7AFRJIgpIZWxsbwY7AFRJIg1mYXJld2VsbAY7AFRJIgxHb29kYnllBjsAVDoJQG5vdzA='
session = Marshal.load(Base64.decode64(rails_3_2_cookie))
hash = Flash::FlashHash.from_session_value(session['flash'])
- assert_equal({'flashes' => {'message' => 'Hello'}, 'discard' => %w[message]}, hash.to_session_value)
+ assert_equal({'greeting' => 'Hello'}, hash.to_hash)
+ assert_equal(nil, hash.to_session_value)
end
def test_from_session_value_on_json_serializer
- decrypted_data = "{ \"session_id\":\"d98bdf6d129618fc2548c354c161cfb5\", \"flash\":{\"discard\":[], \"flashes\":{\"message\":\"hey you\"}} }"
+ decrypted_data = "{ \"session_id\":\"d98bdf6d129618fc2548c354c161cfb5\", \"flash\":{\"discard\":[\"farewell\"], \"flashes\":{\"greeting\":\"Hello\",\"farewell\":\"Goodbye\"}} }"
session = ActionDispatch::Cookies::JsonSerializer.load(decrypted_data)
hash = Flash::FlashHash.from_session_value(session['flash'])
- assert_equal({'discard' => %w[message], 'flashes' => { 'message' => 'hey you'}}, hash.to_session_value)
- assert_equal "hey you", hash[:message]
- assert_equal "hey you", hash["message"]
+ assert_equal({'greeting' => 'Hello'}, hash.to_hash)
+ assert_equal(nil, hash.to_session_value)
+ assert_equal "Hello", hash[:greeting]
+ assert_equal "Hello", hash["greeting"]
end
def test_empty?
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 3720a920d0..0ff0a1ef61 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -288,16 +288,16 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest
def test_setting_flash_does_not_raise_in_following_requests
with_test_route_set do
env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
- get '/set_flash', nil, env
- get '/set_flash', nil, env
+ get '/set_flash', env: env
+ get '/set_flash', env: env
end
end
def test_setting_flash_now_does_not_raise_in_following_requests
with_test_route_set do
env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new }
- get '/set_flash_now', nil, env
- get '/set_flash_now', nil, env
+ get '/set_flash_now', env: env
+ get '/set_flash_now', env: env
end
end
@@ -312,9 +312,11 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest
private
# Overwrite get to send SessionSecret in env hash
- def get(path, parameters = nil, env = {})
- env["action_dispatch.key_generator"] ||= Generator
- super
+ def get(path, *args)
+ args[0] ||= {}
+ args[0][:env] ||= {}
+ args[0][:env]["action_dispatch.key_generator"] ||= Generator
+ super(path, *args)
end
def with_test_route_set
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
index 00d4612ac9..04222745d9 100644
--- a/actionpack/test/controller/force_ssl_test.rb
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -100,7 +100,7 @@ class ForceSSLControllerLevelTest < ActionController::TestCase
end
def test_banana_redirects_to_https_with_extra_params
- get :banana, :token => "secret"
+ get :banana, params: { token: "secret" }
assert_response 301
assert_equal "https://test.host/force_ssl_controller_level/banana?token=secret", redirect_to_url
end
@@ -273,7 +273,7 @@ class ForceSSLFormatTest < ActionController::TestCase
get '/foo', :to => 'force_ssl_controller_level#banana'
end
- get :banana, :format => :json
+ get :banana, format: :json
assert_response 301
assert_equal 'https://test.host/foo.json', redirect_to_url
end
@@ -294,7 +294,7 @@ class ForceSSLOptionalSegmentsTest < ActionController::TestCase
end
@request.env['PATH_INFO'] = '/en/foo'
- get :banana, :locale => 'en'
+ get :banana, params: { locale: 'en' }
assert_equal 'en', @controller.params[:locale]
assert_response 301
assert_equal 'https://test.host/en/foo', redirect_to_url
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 20f99f19ee..e263ed341f 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -29,7 +29,7 @@ module ImpressiveLibrary
def useful_function() end
end
-ActionController::Base.send :include, ImpressiveLibrary
+ActionController::Base.include(ImpressiveLibrary)
class JustMeController < ActionController::Base
clear_helpers
@@ -60,6 +60,12 @@ class HelpersPathsController < ActionController::Base
end
end
+class HelpersTypoController < ActionController::Base
+ path = File.expand_path('../../fixtures/helpers_typo', __FILE__)
+ $:.unshift(path)
+ self.helpers_path = path
+end
+
module LocalAbcHelper
def a() end
def b() end
@@ -82,6 +88,22 @@ class HelperPathsTest < ActiveSupport::TestCase
end
end
+class HelpersTypoControllerTest < ActiveSupport::TestCase
+ def setup
+ @autoload_paths = ActiveSupport::Dependencies.autoload_paths
+ ActiveSupport::Dependencies.autoload_paths = Array(HelpersTypoController.helpers_path)
+ end
+
+ def test_helper_typo_error_message
+ e = assert_raise(NameError) { HelpersTypoController.helper 'admin/users' }
+ assert_equal "Couldn't find Admin::UsersHelper, expected it to be defined in helpers/admin/users_helper.rb", e.message
+ end
+
+ def teardown
+ ActiveSupport::Dependencies.autoload_paths = @autoload_paths
+ end
+end
+
class HelperTest < ActiveSupport::TestCase
class TestController < ActionController::Base
attr_accessor :delegate_attr
@@ -201,10 +223,10 @@ class HelperTest < ActiveSupport::TestCase
# fun/pdf_helper.rb
assert methods.include?(:foobar)
end
-
+
def test_helper_proxy_config
AllHelpersController.config.my_var = 'smth'
-
+
assert_equal 'smth', AllHelpersController.helpers.config.my_var
end
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
index 9052fc6962..20962a90cb 100644
--- a/actionpack/test/controller/http_basic_authentication_test.rb
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -83,6 +83,13 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
assert_response :unauthorized
assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and long credentials"
end
+
+ test "unsuccessful authentication with #{header.downcase} and no credentials" do
+ get :show
+
+ assert_response :unauthorized
+ assert_equal "HTTP Basic: Access denied.\n", @response.body, "Authentication didn't fail for request header #{header} and no credentials"
+ end
end
def test_encode_credentials_has_no_newline
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index 8c6c8a0aa7..a758df2ec6 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -162,17 +162,36 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
assert_equal(expected, actual)
end
+ test "token_and_options returns right token when token key is not specified in header" do
+ token = "rcHu+HzSFw89Ypyhn/896A="
+
+ actual = ActionController::HttpAuthentication::Token.token_and_options(
+ sample_request_without_token_key(token)
+ ).first
+
+ expected = token
+ assert_equal(expected, actual)
+ end
+
private
def sample_request(token, options = {nonce: "def"})
authorization = options.inject([%{Token token="#{token}"}]) do |arr, (k, v)|
arr << "#{k}=\"#{v}\""
end.join(", ")
- @sample_request ||= OpenStruct.new authorization: authorization
+ mock_authorization_request(authorization)
end
def malformed_request
- @malformed_request ||= OpenStruct.new authorization: %{Token token=}
+ mock_authorization_request(%{Token token=})
+ end
+
+ def sample_request_without_token_key(token)
+ mock_authorization_request(%{Token #{token}})
+ end
+
+ def mock_authorization_request(authorization)
+ OpenStruct.new(authorization: authorization)
end
def encode_credentials(token, options = {})
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index c6380c7ffd..9ab1549e8e 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -32,158 +32,275 @@ class SessionTest < ActiveSupport::TestCase
def test_request_via_redirect_uses_given_method
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.expects(:process).with(:put, path, args, headers)
+ @session.expects(:process).with(:put, path, params: args, headers: headers)
@session.stubs(:redirect?).returns(false)
- @session.request_via_redirect(:put, path, args, headers)
+ @session.request_via_redirect(:put, path, params: args, headers: headers)
+ end
+
+ def test_deprecated_request_via_redirect_uses_given_method
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
+ @session.expects(:process).with(:put, path, params: args, headers: headers)
+ @session.stubs(:redirect?).returns(false)
+ assert_deprecated { @session.request_via_redirect(:put, path, args, headers) }
end
def test_request_via_redirect_follows_redirects
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
@session.stubs(:redirect?).returns(true, true, false)
@session.expects(:follow_redirect!).times(2)
- @session.request_via_redirect(:get, path, args, headers)
+ @session.request_via_redirect(:get, path, params: args, headers: headers)
end
def test_request_via_redirect_returns_status
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
@session.stubs(:redirect?).returns(false)
@session.stubs(:status).returns(200)
- assert_equal 200, @session.request_via_redirect(:get, path, args, headers)
+ assert_equal 200, @session.request_via_redirect(:get, path, params: args, headers: headers)
end
- def test_get_via_redirect
- path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ def test_deprecated_get_via_redirect
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:get, path, args, headers)
- @session.get_via_redirect(path, args, headers)
+
+ assert_deprecated do
+ @session.get_via_redirect(path, args, headers)
+ end
end
- def test_post_via_redirect
- path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ def test_deprecated_post_via_redirect
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:post, path, args, headers)
- @session.post_via_redirect(path, args, headers)
+
+ assert_deprecated do
+ @session.post_via_redirect(path, args, headers)
+ end
end
- def test_patch_via_redirect
- path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ def test_deprecated_patch_via_redirect
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:patch, path, args, headers)
- @session.patch_via_redirect(path, args, headers)
+
+ assert_deprecated do
+ @session.patch_via_redirect(path, args, headers)
+ end
end
- def test_put_via_redirect
- path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ def test_deprecated_put_via_redirect
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:put, path, args, headers)
- @session.put_via_redirect(path, args, headers)
+
+ assert_deprecated do
+ @session.put_via_redirect(path, args, headers)
+ end
end
- def test_delete_via_redirect
- path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" }
+ def test_deprecated_delete_via_redirect
+ path = "/somepath"; args = { id: '1' }; headers = { "X-Test-Header" => "testvalue" }
@session.expects(:request_via_redirect).with(:delete, path, args, headers)
- @session.delete_via_redirect(path, args, headers)
+
+ assert_deprecated do
+ @session.delete_via_redirect(path, args, headers)
+ end
end
def test_get
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:get,path,params,headers)
- @session.get(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers)
+ @session.get(path, params: params, headers: headers)
+ end
+
+ def test_get_with_env_and_headers
+ path = "/index"; params = "blah"; headers = { location: 'blah' }; env = { 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers, env: env)
+ @session.get(path, params: params, headers: headers, env: env)
+ end
+
+ def test_deprecated_get
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.get(path, params, headers)
+ }
end
def test_post
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:post,path,params,headers)
- @session.post(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:post, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.post(path, params, headers)
+ }
+ end
+
+ def test_deprecated_post
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:post, path, params: params, headers: headers)
+ @session.post(path, params: params, headers: headers)
end
def test_patch
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:patch,path,params,headers)
- @session.patch(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:patch, path, params: params, headers: headers)
+ @session.patch(path, params: params, headers: headers)
+ end
+
+ def test_deprecated_patch
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:patch, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.patch(path, params, headers)
+ }
end
def test_put
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:put,path,params,headers)
- @session.put(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:put, path, params: params, headers: headers)
+ @session.put(path, params: params, headers: headers)
+ end
+
+ def test_deprecated_put
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:put, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.put(path, params, headers)
+ }
end
def test_delete
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:delete,path,params,headers)
- @session.delete(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:delete, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.delete(path,params,headers)
+ }
+ end
+
+ def test_deprecated_delete
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:delete, path, params: params, headers: headers)
+ @session.delete(path, params: params, headers: headers)
end
def test_head
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- @session.expects(:process).with(:head,path,params,headers)
- @session.head(path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:head, path, params: params, headers: headers)
+ @session.head(path, params: params, headers: headers)
+ end
+
+ def deprecated_test_head
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:head, path, params: params, headers: headers)
+ assert_deprecated {
+ @session.head(path, params, headers)
+ }
end
def test_xml_http_request_get
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:get,path,params,headers_after_xhr)
- @session.xml_http_request(:get,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
+ @session.get(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_get
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
+ @session.get(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_args_xml_http_request_get
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:get, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) {
+ @session.xml_http_request(:get, path, params, headers)
+ }
end
def test_xml_http_request_post
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:post,path,params,headers_after_xhr)
- @session.xml_http_request(:post,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
+ @session.post(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_post
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
+ @session.post(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_args_xml_http_request_post
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:post, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:post,path,params,headers) }
end
def test_xml_http_request_patch
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:patch,path,params,headers_after_xhr)
- @session.xml_http_request(:patch,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
+ @session.patch(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_patch
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
+ @session.patch(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_args_xml_http_request_patch
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:patch, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:patch,path,params,headers) }
end
def test_xml_http_request_put
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:put,path,params,headers_after_xhr)
- @session.xml_http_request(:put,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
+ @session.put(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_put
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
+ @session.put(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_args_xml_http_request_put
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:put, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:put, path, params, headers) }
end
def test_xml_http_request_delete
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:delete,path,params,headers_after_xhr)
- @session.xml_http_request(:delete,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
+ @session.delete(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_delete
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
+ assert_deprecated { @session.xml_http_request(:delete, path, params: params, headers: headers) }
+ end
+
+ def test_deprecated_args_xml_http_request_delete
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:delete, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:delete, path, params, headers) }
end
def test_xml_http_request_head
- path = "/index"; params = "blah"; headers = {:location => 'blah'}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
- "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
- )
- @session.expects(:process).with(:head,path,params,headers_after_xhr)
- @session.xml_http_request(:head,path,params,headers)
- end
-
- def test_xml_http_request_override_accept
- path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"}
- headers_after_xhr = headers.merge(
- "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
- )
- @session.expects(:process).with(:post,path,params,headers_after_xhr)
- @session.xml_http_request(:post,path,params,headers)
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
+ @session.head(path, params: params, headers: headers, xhr: true)
+ end
+
+ def test_deprecated_xml_http_request_head
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
+ assert_deprecated(/xml_http_request/) { @session.xml_http_request(:head, path, params: params, headers: headers) }
+ end
+
+ def test_deprecated_args_xml_http_request_head
+ path = "/index"; params = "blah"; headers = { location: 'blah' }
+ @session.expects(:process).with(:head, path, params: params, headers: headers, xhr: true)
+ assert_deprecated { @session.xml_http_request(:head, path, params, headers) }
end
end
@@ -279,6 +396,11 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
def redirect
redirect_to action_url('get')
end
+
+ def remove_default_header
+ response.headers.except! 'X-Frame-Options'
+ head :ok
+ end
end
def test_get
@@ -292,7 +414,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_equal({}, cookies.to_hash)
assert_equal "OK", body
assert_equal "OK", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
end
end
@@ -308,7 +430,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_equal({}, cookies.to_hash)
assert_equal "Created", body
assert_equal "Created", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
end
end
@@ -368,7 +490,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_response :redirect
assert_response :found
assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
follow_redirect!
@@ -383,7 +505,19 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
def test_xml_http_request_get
with_test_route_set do
- xhr :get, '/get'
+ get '/get', xhr: true
+ assert_equal 200, status
+ assert_equal "OK", status_message
+ assert_response 200
+ assert_response :success
+ assert_response :ok
+ assert_equal "JS OK", response.body
+ end
+ end
+
+ def test_deprecated_xml_http_request_get
+ with_test_route_set do
+ assert_deprecated { xhr :get, '/get' }
assert_equal 200, status
assert_equal "OK", status_message
assert_response 200
@@ -395,7 +529,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
def test_request_with_bad_format
with_test_route_set do
- xhr :get, '/get.php'
+ get '/get.php', xhr: true
assert_equal 406, status
assert_response 406
assert_response :not_acceptable
@@ -418,7 +552,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
def test_get_with_parameters
with_test_route_set do
- get '/get_with_params', :foo => "bar"
+ get '/get_with_params', params: { foo: "bar" }
assert_equal '/get_with_params', request.env["PATH_INFO"]
assert_equal '/get_with_params', request.path_info
assert_equal 'foo=bar', request.env["QUERY_STRING"]
@@ -506,6 +640,24 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
end
+ def test_removed_default_headers_on_test_response_are_not_reapplied
+ with_test_route_set do
+ begin
+ header_to_remove = 'X-Frame-Options'
+ original_default_headers = ActionDispatch::Response.default_headers
+ ActionDispatch::Response.default_headers = {
+ 'X-Content-Type-Options' => 'nosniff',
+ header_to_remove => 'SAMEORIGIN',
+ }
+ get '/remove_default_header'
+ assert_includes headers, 'X-Content-Type-Options'
+ assert_not_includes headers, header_to_remove, "Should not contain removed default header"
+ ensure
+ ActionDispatch::Response.default_headers = original_default_headers
+ end
+ end
+ end
+
private
def with_test_route_set
with_routing do |set|
@@ -521,7 +673,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
get 'get/:action', :to => controller, :as => :get_action
end
- self.singleton_class.send(:include, set.url_helpers)
+ self.singleton_class.include(set.url_helpers)
yield
end
@@ -565,14 +717,22 @@ class MetalIntegrationTest < ActionDispatch::IntegrationTest
end
def test_pass_headers
- get "/success", {}, "Referer" => "http://www.example.com/foo", "Host" => "http://nohost.com"
+ get "/success", headers: {"Referer" => "http://www.example.com/foo", "Host" => "http://nohost.com"}
assert_equal "http://nohost.com", @request.env["HTTP_HOST"]
assert_equal "http://www.example.com/foo", @request.env["HTTP_REFERER"]
end
+ def test_pass_headers_and_env
+ get "/success", headers: { "X-Test-Header" => "value" }, env: { "HTTP_REFERER" => "http://test.com/", "HTTP_HOST" => "http://test.com" }
+
+ assert_equal "http://test.com", @request.env["HTTP_HOST"]
+ assert_equal "http://test.com/", @request.env["HTTP_REFERER"]
+ assert_equal "value", @request.env["HTTP_X_TEST_HEADER"]
+ end
+
def test_pass_env
- get "/success", {}, "HTTP_REFERER" => "http://test.com/", "HTTP_HOST" => "http://test.com"
+ get "/success", env: { "HTTP_REFERER" => "http://test.com/", "HTTP_HOST" => "http://test.com" }
assert_equal "http://test.com", @request.env["HTTP_HOST"]
assert_equal "http://test.com/", @request.env["HTTP_REFERER"]
@@ -615,6 +775,8 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
get 'bar', :to => 'application_integration_test/test#index', :as => :bar
mount MountedApp => '/mounted', :as => "mounted"
+ get 'fooz' => proc { |env| [ 200, {'X-Cascade' => 'pass'}, [ "omg" ] ] }, :anchor => false
+ get 'fooz', :to => 'application_integration_test/test#index'
end
def app
@@ -631,6 +793,12 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
assert_equal '/mounted/baz', mounted.baz_path
end
+ test "path after cascade pass" do
+ get '/fooz'
+ assert_equal 'index', response.body
+ assert_equal '/fooz', path
+ end
+
test "route helpers after controller access" do
get '/'
assert_equal '/', empty_string_path
@@ -654,7 +822,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
test "process do not modify the env passed as argument" do
env = { :SERVER_NAME => 'server', 'action_dispatch.custom' => 'custom' }
old_env = env.dup
- get '/foo', nil, env
+ get '/foo', env: env
assert_equal old_env, env
end
end
@@ -684,7 +852,7 @@ class EnvironmentFilterIntegrationTest < ActionDispatch::IntegrationTest
end
test "filters rack request form vars" do
- post "/post", :username => 'cjolly', :password => 'secret'
+ post "/post", params: { username: 'cjolly', password: 'secret' }
assert_equal 'cjolly', request.filtered_parameters['username']
assert_equal '[FILTERED]', request.filtered_parameters['password']
@@ -806,3 +974,63 @@ class HeadWithStatusActionIntegrationTest < ActionDispatch::IntegrationTest
assert_response :ok
end
end
+
+class IntegrationWithRoutingTest < ActionDispatch::IntegrationTest
+ class FooController < ActionController::Base
+ def index
+ render plain: 'ok'
+ end
+ end
+
+ def test_with_routing_resets_session
+ klass_namespace = self.class.name.underscore
+
+ with_routing do |routes|
+ routes.draw do
+ namespace klass_namespace do
+ resources :foo, path: '/with'
+ end
+ end
+
+ get '/integration_with_routing_test/with'
+ assert_response 200
+ assert_equal 'ok', response.body
+ end
+
+ with_routing do |routes|
+ routes.draw do
+ namespace klass_namespace do
+ resources :foo, path: '/routing'
+ end
+ end
+
+ get '/integration_with_routing_test/routing'
+ assert_response 200
+ assert_equal 'ok', response.body
+ end
+ end
+end
+
+# to work in contexts like rspec before(:all)
+class IntegrationRequestsWithoutSetup < ActionDispatch::IntegrationTest
+ self._setup_callbacks = []
+ self._teardown_callbacks = []
+
+ class FooController < ActionController::Base
+ def ok
+ cookies[:key] = 'ok'
+ render plain: 'ok'
+ end
+ end
+
+ def test_request
+ with_routing do |routes|
+ routes.draw { get ':action' => FooController }
+ get '/ok'
+
+ assert_response 200
+ assert_equal 'ok', response.body
+ assert_equal 'ok', cookies['key']
+ end
+ end
+end
diff --git a/actionpack/test/controller/localized_templates_test.rb b/actionpack/test/controller/localized_templates_test.rb
index 27871ef351..3576015513 100644
--- a/actionpack/test/controller/localized_templates_test.rb
+++ b/actionpack/test/controller/localized_templates_test.rb
@@ -19,7 +19,7 @@ class LocalizedTemplatesTest < ActionController::TestCase
def test_localized_template_is_used
I18n.locale = :de
get :hello_world
- assert_equal "Gutten Tag", @response.body
+ assert_equal "Guten Tag", @response.body
end
def test_default_locale_template_is_used_when_locale_is_missing
@@ -30,11 +30,11 @@ class LocalizedTemplatesTest < ActionController::TestCase
def test_use_fallback_locales
I18n.locale = :"de-AT"
- I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
+ I18n.backend.class.include(I18n::Backend::Fallbacks)
I18n.fallbacks[:"de-AT"] = [:de]
get :hello_world
- assert_equal "Gutten Tag", @response.body
+ assert_equal "Guten Tag", @response.body
end
def test_localized_template_has_correct_header_with_no_format_in_template_name
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index 49be7caf38..03a4ad7823 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -73,6 +73,16 @@ module Another
def with_action_not_found
raise AbstractController::ActionNotFound
end
+
+ def append_info_to_payload(payload)
+ super
+ payload[:test_key] = "test_value"
+ @last_payload = payload
+ end
+
+ def last_payload
+ @last_payload
+ end
end
end
@@ -130,7 +140,7 @@ class ACLogSubscriberTest < ActionController::TestCase
end
def test_process_action_with_parameters
- get :show, :id => '10'
+ get :show, params: { id: '10' }
wait
assert_equal 3, logs.size
@@ -138,8 +148,8 @@ class ACLogSubscriberTest < ActionController::TestCase
end
def test_multiple_process_with_parameters
- get :show, :id => '10'
- get :show, :id => '20'
+ get :show, params: { id: '10' }
+ get :show, params: { id: '20' }
wait
@@ -150,7 +160,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def test_process_action_with_wrapped_parameters
@request.env['CONTENT_TYPE'] = 'application/json'
- post :show, :id => '10', :name => 'jose'
+ post :show, params: { id: '10', name: 'jose' }
wait
assert_equal 3, logs.size
@@ -163,10 +173,22 @@ class ACLogSubscriberTest < ActionController::TestCase
assert_match(/\(Views: [\d.]+ms\)/, logs[1])
end
+ def test_append_info_to_payload_is_called_even_with_exception
+ begin
+ get :with_exception
+ wait
+ rescue Exception
+ end
+
+ assert_equal "test_value", @controller.last_payload[:test_key]
+ end
+
def test_process_action_with_filter_parameters
@request.env["action_dispatch.parameter_filter"] = [:lifo, :amount]
- get :show, :lifo => 'Pratik', :amount => '420', :step => '1'
+ get :show, params: {
+ lifo: 'Pratik', amount: '420', step: '1'
+ }
wait
params = logs[1]
diff --git a/actionpack/test/controller/mime/accept_format_test.rb b/actionpack/test/controller/mime/accept_format_test.rb
index 811c507af2..e20c08da4e 100644
--- a/actionpack/test/controller/mime/accept_format_test.rb
+++ b/actionpack/test/controller/mime/accept_format_test.rb
@@ -11,7 +11,7 @@ end
class StarStarMimeControllerTest < ActionController::TestCase
def test_javascript_with_format
@request.accept = "text/javascript"
- get :index, :format => 'js'
+ get :index, format: 'js'
assert_match "function addition(a,b){ return a+b; }", @response.body
end
@@ -86,7 +86,7 @@ class MimeControllerLayoutsTest < ActionController::TestCase
end
def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout
- get :index, :format => :js
+ get :index, format: :js
assert_equal "Hello Firefox", @response.body
end
end
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index 1bc7ad3015..1f5f66dc80 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -310,17 +310,17 @@ class RespondToControllerTest < ActionController::TestCase
def test_js_or_html
@request.accept = "text/javascript, text/html"
- xhr :get, :js_or_html
+ get :js_or_html, xhr: true
assert_equal 'JS', @response.body
@request.accept = "text/javascript, text/html"
- xhr :get, :html_or_xml
+ get :html_or_xml, xhr: true
assert_equal 'HTML', @response.body
@request.accept = "text/javascript, text/html"
assert_raises(ActionController::UnknownFormat) do
- xhr :get, :just_xml
+ get :just_xml, xhr: true
end
end
@@ -335,13 +335,13 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_json_or_yaml
- xhr :get, :json_or_yaml
+ get :json_or_yaml, xhr: true
assert_equal 'JSON', @response.body
- get :json_or_yaml, :format => 'json'
+ get :json_or_yaml, format: 'json'
assert_equal 'JSON', @response.body
- get :json_or_yaml, :format => 'yaml'
+ get :json_or_yaml, format: 'yaml'
assert_equal 'YAML', @response.body
{ 'YAML' => %w(text/yaml),
@@ -357,13 +357,13 @@ class RespondToControllerTest < ActionController::TestCase
def test_js_or_anything
@request.accept = "text/javascript, */*"
- xhr :get, :js_or_html
+ get :js_or_html, xhr: true
assert_equal 'JS', @response.body
- xhr :get, :html_or_xml
+ get :html_or_xml, xhr: true
assert_equal 'HTML', @response.body
- xhr :get, :just_xml
+ get :just_xml, xhr: true
assert_equal 'XML', @response.body
end
@@ -408,14 +408,14 @@ class RespondToControllerTest < ActionController::TestCase
def test_with_atom_content_type
@request.accept = ""
@request.env["CONTENT_TYPE"] = "application/atom+xml"
- xhr :get, :made_for_content_type
+ get :made_for_content_type, xhr: true
assert_equal "ATOM", @response.body
end
def test_with_rss_content_type
@request.accept = ""
@request.env["CONTENT_TYPE"] = "application/rss+xml"
- xhr :get, :made_for_content_type
+ get :made_for_content_type, xhr: true
assert_equal "RSS", @response.body
end
@@ -474,7 +474,7 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_handle_any_any_parameter_format
- get :handle_any_any, {:format=>'html'}
+ get :handle_any_any, format: 'html'
assert_equal 'HTML', @response.body
end
@@ -497,7 +497,7 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_handle_any_any_unkown_format
- get :handle_any_any, { format: 'php' }
+ get :handle_any_any, format: 'php'
assert_equal 'Whatever you ask for, I got it', @response.body
end
@@ -525,18 +525,18 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_xhr
- xhr :get, :js_or_html
+ get :js_or_html, xhr: true
assert_equal 'JS', @response.body
end
def test_custom_constant
- get :custom_constant_handling, :format => "mobile"
+ get :custom_constant_handling, format: "mobile"
assert_equal "text/x-mobile", @response.content_type
assert_equal "Mobile", @response.body
end
def test_custom_constant_handling_without_block
- get :custom_constant_handling_without_block, :format => "mobile"
+ get :custom_constant_handling_without_block, format: "mobile"
assert_equal "text/x-mobile", @response.content_type
assert_equal "Mobile", @response.body
end
@@ -545,13 +545,13 @@ class RespondToControllerTest < ActionController::TestCase
get :html_xml_or_rss
assert_equal "HTML", @response.body
- get :html_xml_or_rss, :format => "html"
+ get :html_xml_or_rss, format: "html"
assert_equal "HTML", @response.body
- get :html_xml_or_rss, :format => "xml"
+ get :html_xml_or_rss, format: "xml"
assert_equal "XML", @response.body
- get :html_xml_or_rss, :format => "rss"
+ get :html_xml_or_rss, format: "rss"
assert_equal "RSS", @response.body
end
@@ -559,12 +559,12 @@ class RespondToControllerTest < ActionController::TestCase
get :forced_xml
assert_equal "XML", @response.body
- get :forced_xml, :format => "html"
+ get :forced_xml, format: "html"
assert_equal "XML", @response.body
end
def test_extension_synonyms
- get :html_xml_or_rss, :format => "xhtml"
+ get :html_xml_or_rss, format: "xhtml"
assert_equal "HTML", @response.body
end
@@ -579,17 +579,17 @@ class RespondToControllerTest < ActionController::TestCase
end
get :using_defaults
- assert_equal "using_defaults - #{[:html].to_s}", @response.body
+ assert_equal "using_defaults - #{[:html]}", @response.body
- get :using_defaults, :format => "xml"
- assert_equal "using_defaults - #{[:xml].to_s}", @response.body
+ get :using_defaults, format: "xml"
+ assert_equal "using_defaults - #{[:xml]}", @response.body
end
def test_format_with_custom_response_type
get :iphone_with_html_response_type
assert_equal '<html><div id="html">Hello future from Firefox!</div></html>', @response.body
- get :iphone_with_html_response_type, :format => "iphone"
+ get :iphone_with_html_response_type, format: "iphone"
assert_equal "text/html", @response.content_type
assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body
end
@@ -603,7 +603,7 @@ class RespondToControllerTest < ActionController::TestCase
def test_invalid_format
assert_raises(ActionController::UnknownFormat) do
- get :using_defaults, :format => "invalidformat"
+ get :using_defaults, format: "invalidformat"
end
end
diff --git a/actionpack/test/controller/mime/responders_test.rb b/actionpack/test/controller/mime/responders_test.rb
deleted file mode 100644
index 032b4c0ab1..0000000000
--- a/actionpack/test/controller/mime/responders_test.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-require 'abstract_unit'
-require 'controller/fake_models'
-
-class ResponderTest < ActionController::TestCase
- def test_class_level_respond_to
- e = assert_raises(NoMethodError) do
- Class.new(ActionController::Base) do
- respond_to :json
- end
- end
-
- assert_includes e.message, '`responders` gem'
- assert_includes e.message, '~> 2.0'
- end
-
- def test_respond_with
- klass = Class.new(ActionController::Base) do
- def index
- respond_with Customer.new("david", 13)
- end
- end
-
- @controller = klass.new
-
- e = assert_raises(NoMethodError) do
- get :index
- end
-
- assert_includes e.message, '`responders` gem'
- assert_includes e.message, '~> 2.0'
- end
-end
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 246ba099af..710c428dcc 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -31,6 +31,15 @@ module BareMetalTest
controller.index
assert_equal ["Hello world"], controller.response_body
end
+
+ test "connect a request to controller instance without dispatch" do
+ env = {}
+ controller = BareController.new
+ controller.set_request! ActionDispatch::Request.new(env)
+ assert controller.request
+ assert controller.response
+ assert env['action_controller.instance']
+ end
end
class HeadController < ActionController::Metal
diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
index 5fd5946619..c8166280fc 100644
--- a/actionpack/test/controller/new_base/content_negotiation_test.rb
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -15,12 +15,12 @@ module ContentNegotiation
class TestContentNegotiation < Rack::TestCase
test "A */* Accept header will return HTML" do
- get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*"
+ get "/content_negotiation/basic/hello", headers: { "HTTP_ACCEPT" => "*/*" }
assert_body "Hello world */*!"
end
test "Not all mimes are converted to symbol" do
- get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another"
+ get "/content_negotiation/basic/all", headers: { "HTTP_ACCEPT" => "text/plain, mime/another" }
assert_body '[:text, "mime/another"]'
end
end
diff --git a/actionpack/test/controller/new_base/content_type_test.rb b/actionpack/test/controller/new_base/content_type_test.rb
index 9b57641e75..88453988dd 100644
--- a/actionpack/test/controller/new_base/content_type_test.rb
+++ b/actionpack/test/controller/new_base/content_type_test.rb
@@ -76,7 +76,7 @@ module ContentType
end
test "sets Content-Type as application/xml when rendering *.xml.erb" do
- get "/content_type/implied/i_am_xml_erb", "format" => "xml"
+ get "/content_type/implied/i_am_xml_erb", params: { "format" => "xml" }
assert_header "Content-Type", "application/xml; charset=utf-8"
end
@@ -88,7 +88,7 @@ module ContentType
end
test "sets Content-Type as application/xml when rendering *.xml.builder" do
- get "/content_type/implied/i_am_xml_builder", "format" => "xml"
+ get "/content_type/implied/i_am_xml_builder", params: { "format" => "xml" }
assert_header "Content-Type", "application/xml; charset=utf-8"
end
diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb
index 475bf9d3c9..3bf1dd0ede 100644
--- a/actionpack/test/controller/new_base/render_action_test.rb
+++ b/actionpack/test/controller/new_base/render_action_test.rb
@@ -88,7 +88,7 @@ module RenderAction
test "rendering with layout => true" do
assert_raise(ArgumentError) do
- get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
+ get "/render_action/basic/hello_world_with_layout", headers: { "action_dispatch.show_exceptions" => false }
end
end
@@ -108,7 +108,7 @@ module RenderAction
test "rendering with layout => 'greetings'" do
assert_raise(ActionView::MissingTemplate) do
- get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false
+ get "/render_action/basic/hello_world_with_custom_layout", headers: { "action_dispatch.show_exceptions" => false }
end
end
end
diff --git a/actionpack/test/controller/new_base/render_layout_test.rb b/actionpack/test/controller/new_base/render_layout_test.rb
index 4ac40ca405..7ab3777026 100644
--- a/actionpack/test/controller/new_base/render_layout_test.rb
+++ b/actionpack/test/controller/new_base/render_layout_test.rb
@@ -86,7 +86,7 @@ module ControllerLayouts
XML_INSTRUCT = %Q(<?xml version="1.0" encoding="UTF-8"?>\n)
test "if XML is selected, an HTML template is not also selected" do
- get :index, :format => "xml"
+ get :index, params: { format: "xml" }
assert_response XML_INSTRUCT
end
@@ -96,7 +96,7 @@ module ControllerLayouts
end
test "a layout for JS is ignored even if explicitly provided for HTML" do
- get :explicit, { :format => "js" }
+ get :explicit, params: { format: "js" }
assert_response "alert('foo');"
end
end
@@ -120,7 +120,7 @@ module ControllerLayouts
testing ControllerLayouts::FalseLayoutMethodController
test "access false layout returned by a method/proc" do
- get :index, :format => "js"
+ get :index, params: { format: "js" }
assert_response "alert('foo');"
end
end
diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb
index 4c9126ca8c..9ea056194a 100644
--- a/actionpack/test/controller/new_base/render_streaming_test.rb
+++ b/actionpack/test/controller/new_base/render_streaming_test.rb
@@ -97,7 +97,7 @@ module RenderStreaming
end
test "do not stream on HTTP/1.0" do
- get "/render_streaming/basic/hello_world", nil, "HTTP_VERSION" => "HTTP/1.0"
+ get "/render_streaming/basic/hello_world", headers: { "HTTP_VERSION" => "HTTP/1.0" }
assert_body "Hello world, I'm here!"
assert_status 200
assert_equal "22", headers["Content-Length"]
diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
index 42a86b1d0d..19fef718e7 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -111,7 +111,7 @@ module RenderTemplate
end
test "rendering a builder template" do
- get :builder_template, "format" => "xml"
+ get :builder_template, params: { "format" => "xml" }
assert_response "<html>\n <p>Hello</p>\n</html>\n"
end
@@ -126,7 +126,7 @@ module RenderTemplate
assert_body "Hello <strong>this is also raw</strong> in an html template"
assert_status 200
- get :with_implicit_raw, format: 'text'
+ get :with_implicit_raw, params: { format: 'text' }
assert_body "Hello <strong>this is also raw</strong> in a text template"
assert_status 200
diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb
index 5635e16234..11a19ab783 100644
--- a/actionpack/test/controller/new_base/render_test.rb
+++ b/actionpack/test/controller/new_base/render_test.rb
@@ -74,7 +74,7 @@ module Render
end
assert_raises(AbstractController::DoubleRenderError) do
- get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
+ get "/render/double_render", headers: { "action_dispatch.show_exceptions" => false }
end
end
end
@@ -84,13 +84,13 @@ module Render
# Only public methods on actual controllers are callable actions
test "raises an exception when a method of Object is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false
+ get "/render/blank_render/clone", headers: { "action_dispatch.show_exceptions" => false }
end
end
test "raises an exception when a private method is called" do
assert_raises(AbstractController::ActionNotFound) do
- get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false
+ get "/render/blank_render/secretz", headers: { "action_dispatch.show_exceptions" => false }
end
end
end
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index ba98ad7605..2ed486516d 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -280,4 +280,10 @@ class ParametersPermitTest < ActiveSupport::TestCase
assert_equal({ "controller" => "users", "action" => "create" }, params.to_h)
end
+
+ test "to_unsafe_h returns unfiltered params" do
+ assert @params.to_h.is_a? Hash
+ assert_not @params.to_h.is_a? ActionController::Parameters
+ assert_equal @params.to_hash, @params.to_unsafe_h
+ end
end
diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb
index 645ecae220..8bf016d060 100644
--- a/actionpack/test/controller/params_wrapper_test.rb
+++ b/actionpack/test/controller/params_wrapper_test.rb
@@ -40,7 +40,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_filtered_parameters
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_equal @request.filtered_parameters, { 'controller' => 'params_wrapper_test/users', 'action' => 'parse', 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' } }
end
end
@@ -48,7 +48,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_derived_name_from_controller
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({ 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -58,7 +58,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters :person
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({ 'username' => 'sikachu', 'person' => { 'username' => 'sikachu' }})
end
end
@@ -68,7 +68,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters Person
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({ 'username' => 'sikachu', 'person' => { 'username' => 'sikachu' }})
end
end
@@ -78,7 +78,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters :include => :username
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -88,7 +88,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters :exclude => :title
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -98,7 +98,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters :person, :include => :username
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
end
end
@@ -106,7 +106,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_not_enabled_format
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/xml'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer' })
end
end
@@ -115,7 +115,7 @@ class ParamsWrapperTest < ActionController::TestCase
with_default_wrapper_options do
UsersController.wrap_parameters false
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer' })
end
end
@@ -125,7 +125,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters :format => :xml
@request.env['CONTENT_TYPE'] = 'application/xml'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu', 'title' => 'Developer' }})
end
end
@@ -133,7 +133,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_not_wrap_reserved_parameters
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'authenticity_token' => 'pwned', '_method' => 'put', 'utf8' => '&#9731;', 'username' => 'sikachu' }
+ post :parse, params: { 'authenticity_token' => 'pwned', '_method' => 'put', 'utf8' => '&#9731;', 'username' => 'sikachu' }
assert_parameters({ 'authenticity_token' => 'pwned', '_method' => 'put', 'utf8' => '&#9731;', 'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -141,7 +141,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_no_double_wrap_if_key_exists
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'user' => { 'username' => 'sikachu' }}
+ post :parse, params: { 'user' => { 'username' => 'sikachu' }}
assert_parameters({ 'user' => { 'username' => 'sikachu' }})
end
end
@@ -149,7 +149,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_nested_params
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'person' => { 'username' => 'sikachu' }}
+ post :parse, params: { 'person' => { 'username' => 'sikachu' }}
assert_parameters({ 'person' => { 'username' => 'sikachu' }, 'user' => {'person' => { 'username' => 'sikachu' }}})
end
end
@@ -160,7 +160,7 @@ class ParamsWrapperTest < ActionController::TestCase
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -173,7 +173,7 @@ class ParamsWrapperTest < ActionController::TestCase
UsersController.wrap_parameters Person
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }})
end
end
@@ -184,7 +184,7 @@ class ParamsWrapperTest < ActionController::TestCase
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu', 'title' => 'Developer' }})
end
end
@@ -192,7 +192,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_preserves_query_string_params
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- get :parse, { 'user' => { 'username' => 'nixon' } }
+ get :parse, params: { 'user' => { 'username' => 'nixon' } }
assert_parameters(
{'user' => { 'username' => 'nixon' } }
)
@@ -202,7 +202,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_empty_parameter_set
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, {}
+ post :parse, params: {}
assert_parameters(
{'user' => { } }
)
@@ -249,7 +249,7 @@ class NamespacedParamsWrapperTest < ActionController::TestCase
def test_derived_name_from_controller
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({'username' => 'sikachu', 'user' => { 'username' => 'sikachu' }})
end
end
@@ -259,7 +259,7 @@ class NamespacedParamsWrapperTest < ActionController::TestCase
begin
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }})
end
ensure
@@ -272,7 +272,7 @@ class NamespacedParamsWrapperTest < ActionController::TestCase
begin
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'title' => 'Developer' }
+ post :parse, params: { 'username' => 'sikachu', 'title' => 'Developer' }
assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'title' => 'Developer' }})
end
ensure
@@ -299,7 +299,7 @@ class AnonymousControllerParamsWrapperTest < ActionController::TestCase
def test_does_not_implicitly_wrap_params
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({ 'username' => 'sikachu' })
end
end
@@ -308,7 +308,7 @@ class AnonymousControllerParamsWrapperTest < ActionController::TestCase
with_default_wrapper_options do
@controller.class.wrap_parameters(:name => "guest")
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu' }
+ post :parse, params: { 'username' => 'sikachu' }
assert_parameters({ 'username' => 'sikachu', 'guest' => { 'username' => 'sikachu' }})
end
end
@@ -344,7 +344,7 @@ class IrregularInflectionParamsWrapperTest < ActionController::TestCase
with_default_wrapper_options do
@request.env['CONTENT_TYPE'] = 'application/json'
- post :parse, { 'username' => 'sikachu', 'test_attr' => 'test_value' }
+ post :parse, params: { 'username' => 'sikachu', 'test_attr' => 'test_value' }
assert_parameters({ 'username' => 'sikachu', 'test_attr' => 'test_value', 'paramswrappernews_item' => { 'test_attr' => 'test_value' }})
end
end
diff --git a/actionpack/test/controller/permitted_params_test.rb b/actionpack/test/controller/permitted_params_test.rb
index f46249d712..7136fafae5 100644
--- a/actionpack/test/controller/permitted_params_test.rb
+++ b/actionpack/test/controller/permitted_params_test.rb
@@ -14,12 +14,12 @@ class ActionControllerPermittedParamsTest < ActionController::TestCase
tests PeopleController
test "parameters are forbidden" do
- post :create, { person: { name: "Mjallo!" } }
+ post :create, params: { person: { name: "Mjallo!" } }
assert_equal "forbidden", response.body
end
test "parameters can be permitted and are then not forbidden" do
- post :create_with_permit, { person: { name: "Mjallo!" } }
+ post :create_with_permit, params: { person: { name: "Mjallo!" } }
assert_equal "permitted", response.body
end
end
diff --git a/actionpack/test/controller/render_js_test.rb b/actionpack/test/controller/render_js_test.rb
index d550422a2f..6b661de064 100644
--- a/actionpack/test/controller/render_js_test.rb
+++ b/actionpack/test/controller/render_js_test.rb
@@ -22,13 +22,13 @@ class RenderJSTest < ActionController::TestCase
tests TestController
def test_render_vanilla_js
- xhr :get, :render_vanilla_js_hello
+ get :render_vanilla_js_hello, xhr: true
assert_equal "alert('hello')", @response.body
assert_equal "text/javascript", @response.content_type
end
def test_should_render_js_partial
- xhr :get, :show_partial, :format => 'js'
+ get :show_partial, format: 'js', xhr: true
assert_equal 'partial js', @response.body
end
end
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
index ada978aa11..b1ad16bc55 100644
--- a/actionpack/test/controller/render_json_test.rb
+++ b/actionpack/test/controller/render_json_test.rb
@@ -100,13 +100,13 @@ class RenderJsonTest < ActionController::TestCase
end
def test_render_json_with_callback
- xhr :get, :render_json_hello_world_with_callback
+ get :render_json_hello_world_with_callback, xhr: true
assert_equal '/**/alert({"hello":"world"})', @response.body
assert_equal 'text/javascript', @response.content_type
end
def test_render_json_with_custom_content_type
- xhr :get, :render_json_with_custom_content_type
+ get :render_json_with_custom_content_type, xhr: true
assert_equal '{"hello":"world"}', @response.body
assert_equal 'text/javascript', @response.content_type
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index b036b6c08e..488585c7a4 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -58,24 +58,24 @@ class TestController < ActionController::Base
end
end
- def conditional_hello_with_public_header
- if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
- render :action => 'hello_world'
+ class Collection
+ def initialize(records)
+ @records = records
end
- end
- def conditional_hello_with_public_header_with_record
- record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123")
-
- if stale?(record, :public => true)
- render :action => 'hello_world'
+ def maximum(attribute)
+ @records.max_by(&attribute).public_send(attribute)
end
end
- def conditional_hello_with_public_header_and_expires_at
- expires_in 1.minute
- if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true)
- render :action => 'hello_world'
+ def conditional_hello_with_collection_of_records
+ ts = Time.now.utc.beginning_of_day
+
+ record = Struct.new(:updated_at, :cache_key).new(ts, "foo/123")
+ old_record = Struct.new(:updated_at, :cache_key).new(ts - 1.day, "bar/123")
+
+ if stale?(Collection.new([record, old_record]))
+ render action: 'hello_world'
end
end
@@ -129,50 +129,6 @@ class TestController < ActionController::Base
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
- def heading
- head :ok
- end
-
- # :ported:
- def double_render
- render :text => "hello"
- render :text => "world"
- end
-
- def double_redirect
- redirect_to :action => "double_render"
- redirect_to :action => "double_render"
- end
-
- def render_and_redirect
- render :text => "hello"
- redirect_to :action => "double_render"
- end
-
- def render_to_string_and_render
- @stuff = render_to_string :text => "here is some cached stuff"
- render :text => "Hi web users! #{@stuff}"
- end
-
- def render_to_string_with_inline_and_render
- render_to_string :inline => "<%= 'dlrow olleh'.reverse %>"
- render :template => "test/hello_world"
- end
-
- def rendering_with_conflicting_local_vars
- @name = "David"
- render :action => "potential_conflicts"
- end
-
- def hello_world_from_rxml_using_action
- render :action => "hello_world_from_rxml", :handlers => [:builder]
- end
-
- # :deprecated:
- def hello_world_from_rxml_using_template
- render :template => "test/hello_world_from_rxml", :handlers => [:builder]
- end
-
def head_created
head :created
end
@@ -217,6 +173,15 @@ class TestController < ActionController::Base
head :forbidden, :x_custom_header => "something"
end
+ def head_with_no_content
+ # Fill in the headers with dummy data to make
+ # sure they get removed during the testing
+ response.headers["Content-Type"] = "dummy"
+ response.headers["Content-Length"] = 42
+
+ head 204
+ end
+
private
def set_variable_for_layout
@@ -344,7 +309,6 @@ class LastModifiedRenderTest < ActionController::TestCase
assert_equal @last_modified, @response.headers['Last-Modified']
end
-
def test_responds_with_last_modified_with_record
get :conditional_hello_with_record
assert_equal @last_modified, @response.headers['Last-Modified']
@@ -355,6 +319,7 @@ class LastModifiedRenderTest < ActionController::TestCase
get :conditional_hello_with_record
assert_equal 304, @response.status.to_i
assert @response.body.blank?
+ assert_not_nil @response.etag
assert_equal @last_modified, @response.headers['Last-Modified']
end
@@ -373,6 +338,34 @@ class LastModifiedRenderTest < ActionController::TestCase
assert_equal @last_modified, @response.headers['Last-Modified']
end
+ def test_responds_with_last_modified_with_collection_of_records
+ get :conditional_hello_with_collection_of_records
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified_with_collection_of_records
+ @request.if_modified_since = @last_modified
+ get :conditional_hello_with_collection_of_records
+ assert_equal 304, @response.status.to_i
+ assert @response.body.blank?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
+ def test_request_not_modified_but_etag_differs_with_collection_of_records
+ @request.if_modified_since = @last_modified
+ @request.if_none_match = "234"
+ get :conditional_hello_with_collection_of_records
+ assert_response :success
+ end
+
+ def test_request_modified_with_collection_of_records
+ @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT'
+ get :conditional_hello_with_collection_of_records
+ assert_equal 200, @response.status.to_i
+ assert @response.body.present?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+
def test_request_with_bang_gets_last_modified
get :conditional_hello_with_bangs
assert_equal @last_modified, @response.headers['Last-Modified']
@@ -518,21 +511,21 @@ class HeadRenderTest < ActionController::TestCase
end
def test_head_with_symbolic_status
- get :head_with_symbolic_status, :status => "ok"
+ get :head_with_symbolic_status, params: { status: "ok" }
assert_equal 200, @response.status
assert_response :ok
- get :head_with_symbolic_status, :status => "not_found"
+ get :head_with_symbolic_status, params: { status: "not_found" }
assert_equal 404, @response.status
assert_response :not_found
- get :head_with_symbolic_status, :status => "no_content"
+ get :head_with_symbolic_status, params: { status: "no_content" }
assert_equal 204, @response.status
assert !@response.headers.include?('Content-Length')
assert_response :no_content
Rack::Utils::SYMBOL_TO_STATUS_CODE.each do |status, code|
- get :head_with_symbolic_status, :status => status.to_s
+ get :head_with_symbolic_status, params: { status: status.to_s }
assert_equal code, @response.response_code
assert_response status
end
@@ -540,13 +533,21 @@ class HeadRenderTest < ActionController::TestCase
def test_head_with_integer_status
Rack::Utils::HTTP_STATUS_CODES.each do |code, message|
- get :head_with_integer_status, :status => code.to_s
+ get :head_with_integer_status, params: { status: code.to_s }
assert_equal message, @response.message
end
end
+ def test_head_with_no_content
+ get :head_with_no_content
+
+ assert_equal 204, @response.status
+ assert_nil @response.headers["Content-Type"]
+ assert_nil @response.headers["Content-Length"]
+ end
+
def test_head_with_string_status
- get :head_with_string_status, :status => "404 Eat Dirt"
+ get :head_with_string_status, params: { status: "404 Eat Dirt" }
assert_equal 404, @response.response_code
assert_equal "Not Found", @response.message
assert_response :not_found
@@ -560,3 +561,56 @@ class HeadRenderTest < ActionController::TestCase
assert_response :forbidden
end
end
+
+class HttpCacheForeverTest < ActionController::TestCase
+ class HttpCacheForeverController < ActionController::Base
+ def cache_me_forever
+ http_cache_forever(public: params[:public], version: params[:version] || 'v1') do
+ render text: 'hello'
+ end
+ end
+ end
+
+ tests HttpCacheForeverController
+
+ def test_cache_with_public
+ get :cache_me_forever, params: {public: true}
+ assert_equal "max-age=#{100.years.to_i}, public", @response.headers["Cache-Control"]
+ assert_not_nil @response.etag
+ end
+
+ def test_cache_with_private
+ get :cache_me_forever
+ assert_equal "max-age=#{100.years.to_i}, private", @response.headers["Cache-Control"]
+ assert_not_nil @response.etag
+ assert_response :success
+ end
+
+ def test_cache_response_code_with_if_modified_since
+ get :cache_me_forever
+ assert_response :success
+ @request.if_modified_since = @response.headers['Last-Modified']
+ get :cache_me_forever
+ assert_response :not_modified
+ end
+
+ def test_cache_response_code_with_etag
+ get :cache_me_forever
+ assert_response :success
+ @request.if_modified_since = @response.headers['Last-Modified']
+ @request.if_none_match = @response.etag
+
+ get :cache_me_forever
+ assert_response :not_modified
+ @request.if_modified_since = @response.headers['Last-Modified']
+ @request.if_none_match = @response.etag
+
+ get :cache_me_forever, params: {version: 'v2'}
+ assert_response :success
+ @request.if_modified_since = @response.headers['Last-Modified']
+ @request.if_none_match = @response.etag
+
+ get :cache_me_forever, params: {version: 'v2'}
+ assert_response :not_modified
+ end
+end
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
index 4f280c4bec..7a91577b17 100644
--- a/actionpack/test/controller/render_xml_test.rb
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -81,7 +81,7 @@ class RenderXmlTest < ActionController::TestCase
end
def test_should_render_formatted_xml_erb_template
- get :formatted_xml_erb, :format => :xml
+ get :formatted_xml_erb, format: :xml
assert_equal '<test>passed formatted xml erb</test>', @response.body
end
@@ -91,7 +91,7 @@ class RenderXmlTest < ActionController::TestCase
end
def test_should_use_implicit_content_type
- get :implicit_content_type, :format => 'atom'
+ get :implicit_content_type, format: 'atom'
assert_equal Mime::ATOM, @response.content_type
end
end
diff --git a/actionpack/test/controller/renderer_test.rb b/actionpack/test/controller/renderer_test.rb
new file mode 100644
index 0000000000..b55a25430b
--- /dev/null
+++ b/actionpack/test/controller/renderer_test.rb
@@ -0,0 +1,103 @@
+require 'abstract_unit'
+
+class RendererTest < ActiveSupport::TestCase
+ test 'creating with a controller' do
+ controller = CommentsController
+ renderer = ActionController::Renderer.for controller
+
+ assert_equal controller, renderer.controller
+ end
+
+ test 'creating from a controller' do
+ controller = AccountsController
+ renderer = controller.renderer
+
+ assert_equal controller, renderer.controller
+ end
+
+ test 'rendering with a class renderer' do
+ renderer = ApplicationController.renderer
+ content = renderer.render template: 'ruby_template'
+
+ assert_equal 'Hello from Ruby code', content
+ end
+
+ test 'rendering with an instance renderer' do
+ renderer = ApplicationController.renderer.new
+ content = renderer.render file: 'test/hello_world'
+
+ assert_equal 'Hello world!', content
+ end
+
+ test 'rendering with a controller class' do
+ assert_equal 'Hello world!', ApplicationController.render('test/hello_world')
+ end
+
+ test 'rendering with locals' do
+ renderer = ApplicationController.renderer
+ content = renderer.render template: 'test/render_file_with_locals',
+ locals: { secret: 'bar' }
+
+ assert_equal "The secret is bar\n", content
+ end
+
+ test 'rendering with assigns' do
+ renderer = ApplicationController.renderer
+ content = renderer.render template: 'test/render_file_with_ivar',
+ assigns: { secret: 'foo' }
+
+ assert_equal "The secret is foo\n", content
+ end
+
+ test 'rendering with custom env' do
+ renderer = ApplicationController.renderer.new method: 'post'
+ content = renderer.render inline: '<%= request.post? %>'
+
+ assert_equal 'true', content
+ end
+
+ test 'rendering with defaults' do
+ renderer = ApplicationController.renderer
+ renderer.defaults[:https] = true
+ content = renderer.render inline: '<%= request.ssl? %>'
+
+ assert_equal 'true', content
+ end
+
+ test 'same defaults from the same controller' do
+ renderer_defaults = ->(controller) { controller.renderer.defaults }
+
+ assert renderer_defaults[AccountsController].equal? renderer_defaults[AccountsController]
+ assert_not renderer_defaults[AccountsController].equal? renderer_defaults[CommentsController]
+ end
+
+ test 'rendering with different formats' do
+ html = 'Hello world!'
+ xml = "<p>Hello world!</p>\n"
+
+ assert_equal html, render['respond_to/using_defaults']
+ assert_equal xml, render['respond_to/using_defaults.xml.builder']
+ assert_equal xml, render['respond_to/using_defaults', formats: :xml]
+ end
+
+ test 'rendering with helpers' do
+ assert_equal "<p>1\n<br />2</p>", render[inline: '<%= simple_format "1\n2" %>']
+ end
+
+ test 'rendering from inherited renderer' do
+ inherited = Class.new ApplicationController.renderer do
+ defaults[:script_name] = 'script'
+ def render(options)
+ super options.merge(locals: { param: :value })
+ end
+ end
+
+ template = '<%= url_for controller: :foo, action: :bar, param: param %>'
+ assert_equal 'script/foo/bar?param=value', inherited.render(inline: template)
+ end
+
+ private
+ def render
+ @render ||= ApplicationController.renderer.method(:render)
+ end
+end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 3e0bfe8d14..8887f291cf 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -103,6 +103,31 @@ class RequestForgeryProtectionControllerUsingNullSession < ActionController::Bas
end
end
+class PrependProtectForgeryBaseController < ActionController::Base
+ before_action :custom_action
+ attr_accessor :called_callbacks
+
+ def index
+ render inline: 'OK'
+ end
+
+ protected
+
+ def add_called_callback(name)
+ @called_callbacks ||= []
+ @called_callbacks << name
+ end
+
+
+ def custom_action
+ add_called_callback("custom_action")
+ end
+
+ def verify_authenticity_token
+ add_called_callback("verify_authenticity_token")
+ end
+end
+
class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession
self.allow_forgery_protection = false
@@ -237,23 +262,23 @@ module RequestForgeryProtectionTests
end
def test_should_not_allow_xhr_post_without_token
- assert_blocked { xhr :post, :index }
+ assert_blocked { post :index, xhr: true }
end
def test_should_allow_post_with_token
- assert_not_blocked { post :index, :custom_authenticity_token => @token }
+ assert_not_blocked { post :index, params: { custom_authenticity_token: @token } }
end
def test_should_allow_patch_with_token
- assert_not_blocked { patch :index, :custom_authenticity_token => @token }
+ assert_not_blocked { patch :index, params: { custom_authenticity_token: @token } }
end
def test_should_allow_put_with_token
- assert_not_blocked { put :index, :custom_authenticity_token => @token }
+ assert_not_blocked { put :index, params: { custom_authenticity_token: @token } }
end
def test_should_allow_delete_with_token
- assert_not_blocked { delete :index, :custom_authenticity_token => @token }
+ assert_not_blocked { delete :index, params: { custom_authenticity_token: @token } }
end
def test_should_allow_post_with_token_in_header
@@ -315,21 +340,21 @@ module RequestForgeryProtectionTests
get :negotiate_same_origin
end
- assert_cross_origin_not_blocked { xhr :get, :same_origin_js }
- assert_cross_origin_not_blocked { xhr :get, :same_origin_js, format: 'js' }
+ assert_cross_origin_not_blocked { get :same_origin_js, xhr: true }
+ assert_cross_origin_not_blocked { get :same_origin_js, xhr: true, format: 'js'}
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
- xhr :get, :negotiate_same_origin
+ get :negotiate_same_origin, xhr: true
end
end
# Allow non-GET requests since GET is all a remote <script> tag can muster.
def test_should_allow_non_get_js_without_xhr_header
- assert_cross_origin_not_blocked { post :same_origin_js, custom_authenticity_token: @token }
- assert_cross_origin_not_blocked { post :same_origin_js, format: 'js', custom_authenticity_token: @token }
+ assert_cross_origin_not_blocked { post :same_origin_js, params: { custom_authenticity_token: @token } }
+ assert_cross_origin_not_blocked { post :same_origin_js, params: { format: 'js', custom_authenticity_token: @token } }
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
- post :negotiate_same_origin, custom_authenticity_token: @token
+ post :negotiate_same_origin, params: { custom_authenticity_token: @token}
end
end
@@ -341,11 +366,18 @@ module RequestForgeryProtectionTests
get :negotiate_cross_origin
end
- assert_cross_origin_not_blocked { xhr :get, :cross_origin_js }
- assert_cross_origin_not_blocked { xhr :get, :cross_origin_js, format: 'js' }
+ assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true }
+ assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true, format: 'js' }
assert_cross_origin_not_blocked do
@request.accept = 'text/javascript'
- xhr :get, :negotiate_cross_origin
+ get :negotiate_cross_origin, xhr: true
+ end
+ end
+
+ def test_should_not_raise_error_if_token_is_not_a_string
+ @controller.unstub(:valid_authenticity_token?)
+ assert_blocked do
+ patch :index, params: { custom_authenticity_token: { foo: 'bar' } }
end
end
@@ -431,6 +463,41 @@ class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::T
end
end
+class PrependProtectForgeryBaseControllerTest < ActionController::TestCase
+ PrependTrueController = Class.new(PrependProtectForgeryBaseController) do
+ protect_from_forgery prepend: true
+ end
+
+ PrependFalseController = Class.new(PrependProtectForgeryBaseController) do
+ protect_from_forgery prepend: false
+ end
+
+ PrependDefaultController = Class.new(PrependProtectForgeryBaseController) do
+ protect_from_forgery
+ end
+
+ def test_verify_authenticity_token_is_prepended
+ @controller = PrependTrueController.new
+ get :index
+ expected_callback_order = ["verify_authenticity_token", "custom_action"]
+ assert_equal(expected_callback_order, @controller.called_callbacks)
+ end
+
+ def test_verify_authenticity_token_is_not_prepended
+ @controller = PrependFalseController.new
+ get :index
+ expected_callback_order = ["custom_action", "verify_authenticity_token"]
+ assert_equal(expected_callback_order, @controller.called_callbacks)
+ end
+
+ def test_verify_authenticity_token_is_prepended_by_default
+ @controller = PrependDefaultController.new
+ get :index
+ expected_callback_order = ["verify_authenticity_token", "custom_action"]
+ assert_equal(expected_callback_order, @controller.called_callbacks)
+ end
+end
+
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
@@ -483,7 +550,7 @@ class CustomAuthenticityParamControllerTest < ActionController::TestCase
@controller.stubs(:valid_authenticity_token?).returns(:true)
begin
- post :index, :custom_token_name => 'foobar'
+ post :index, params: { custom_token_name: 'foobar' }
assert_equal 0, @logger.logged(:warn).size
ensure
ActionController::Base.logger = @old_logger
@@ -494,7 +561,7 @@ class CustomAuthenticityParamControllerTest < ActionController::TestCase
ActionController::Base.logger = @logger
begin
- post :index, :custom_token_name => 'bazqux'
+ post :index, params: { custom_token_name: 'bazqux' }
assert_equal 1, @logger.logged(:warn).size
ensure
ActionController::Base.logger = @old_logger
diff --git a/actionpack/test/controller/required_params_test.rb b/actionpack/test/controller/required_params_test.rb
index 6803dbbb62..a901e56332 100644
--- a/actionpack/test/controller/required_params_test.rb
+++ b/actionpack/test/controller/required_params_test.rb
@@ -12,21 +12,21 @@ class ActionControllerRequiredParamsTest < ActionController::TestCase
test "missing required parameters will raise exception" do
assert_raise ActionController::ParameterMissing do
- post :create, { magazine: { name: "Mjallo!" } }
+ post :create, params: { magazine: { name: "Mjallo!" } }
end
assert_raise ActionController::ParameterMissing do
- post :create, { book: { title: "Mjallo!" } }
+ post :create, params: { book: { title: "Mjallo!" } }
end
end
test "required parameters that are present will not raise" do
- post :create, { book: { name: "Mjallo!" } }
+ post :create, params: { book: { name: "Mjallo!" } }
assert_response :ok
end
test "required parameters with false value will not raise" do
- post :create, { book: { name: false } }
+ post :create, params: { book: { name: false } }
assert_response :ok
end
end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 0e15883f43..02e7614ba2 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -1184,10 +1184,10 @@ class ResourcesTest < ActionController::TestCase
end
@controller = "#{options[:options][:controller].camelize}Controller".constantize.new
- @controller.singleton_class.send(:include, @routes.url_helpers)
+ @controller.singleton_class.include(@routes.url_helpers)
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
- get :index, options[:options]
+ get :index, params: options[:options]
options[:options].delete :action
path = "#{options[:as] || controller_name}"
@@ -1254,10 +1254,10 @@ class ResourcesTest < ActionController::TestCase
def assert_singleton_named_routes_for(singleton_name, options = {})
(options[:options] ||= {})[:controller] ||= singleton_name.to_s.pluralize
@controller = "#{options[:options][:controller].camelize}Controller".constantize.new
- @controller.singleton_class.send(:include, @routes.url_helpers)
+ @controller.singleton_class.include(@routes.url_helpers)
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
- get :show, options[:options]
+ get :show, params: options[:options]
options[:options].delete :action
full_path = "/#{options[:path_prefix]}#{options[:as] || singleton_name}"
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index c18914cc8e..2d08987ca6 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'abstract_unit'
require 'controller/fake_controllers'
require 'active_support/core_ext/object/with_options'
@@ -884,13 +883,13 @@ class RouteSetTest < ActiveSupport::TestCase
set.draw { get ':controller/(:action(/:id))' }
path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_extra_keys
set.draw { get ':controller/:action/:id' }
extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_generate_extras_not_first
@@ -900,7 +899,7 @@ class RouteSetTest < ActiveSupport::TestCase
end
path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_generate_not_first
@@ -918,7 +917,7 @@ class RouteSetTest < ActiveSupport::TestCase
get ':controller/:action/:id'
end
extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_draw
@@ -1001,6 +1000,9 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "http://test.host/people?baz=bar#location",
controller.send(:index_url, :baz => "bar", :anchor => 'location')
+
+ assert_equal "http://test.host/people", controller.send(:index_url, anchor: nil)
+ assert_equal "http://test.host/people", controller.send(:index_url, anchor: false)
end
def test_named_route_url_method_with_port
@@ -1383,7 +1385,7 @@ class RouteSetTest < ActiveSupport::TestCase
url = controller.url_for({ :controller => "connection", :only_path => true })
assert_equal "/connection/connection", url
- url = controller.url_for({ :use_route => :family_connection,
+ url = controller.url_for({ :use_route => "family_connection",
:controller => "connection", :only_path => true })
assert_equal "/connection", url
end
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index c002cf4d8f..36c57ec9b2 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'abstract_unit'
module TestFileUtils
diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb
index f7eba1ef43..fba5ebba15 100644
--- a/actionpack/test/controller/show_exceptions_test.rb
+++ b/actionpack/test/controller/show_exceptions_test.rb
@@ -58,13 +58,13 @@ module ShowExceptions
class ShowExceptionsOverriddenTest < ActionDispatch::IntegrationTest
test 'show error page' do
@app = ShowExceptionsOverriddenController.action(:boom)
- get '/', {'detailed' => '0'}
+ get '/', params: { 'detailed' => '0' }
assert_equal "500 error fixture\n", body
end
test 'show diagnostics message' do
@app = ShowExceptionsOverriddenController.action(:boom)
- get '/', {'detailed' => '1'}
+ get '/', params: { 'detailed' => '1' }
assert_match(/boom/, body)
end
end
@@ -72,7 +72,7 @@ module ShowExceptions
class ShowExceptionsFormatsTest < ActionDispatch::IntegrationTest
def test_render_json_exception
@app = ShowExceptionsOverriddenController.action(:boom)
- get "/", {}, 'HTTP_ACCEPT' => 'application/json'
+ get "/", headers: { 'HTTP_ACCEPT' => 'application/json' }
assert_response :internal_server_error
assert_equal 'application/json', response.content_type.to_s
assert_equal({ :status => '500', :error => 'Internal Server Error' }.to_json, response.body)
@@ -80,7 +80,7 @@ module ShowExceptions
def test_render_xml_exception
@app = ShowExceptionsOverriddenController.action(:boom)
- get "/", {}, 'HTTP_ACCEPT' => 'application/xml'
+ get "/", headers: { 'HTTP_ACCEPT' => 'application/xml' }
assert_response :internal_server_error
assert_equal 'application/xml', response.content_type.to_s
assert_equal({ :status => '500', :error => 'Internal Server Error' }.to_xml, response.body)
@@ -88,7 +88,7 @@ module ShowExceptions
def test_render_fallback_exception
@app = ShowExceptionsOverriddenController.action(:boom)
- get "/", {}, 'HTTP_ACCEPT' => 'text/csv'
+ get "/", headers: { 'HTTP_ACCEPT' => 'text/csv' }
assert_response :internal_server_error
assert_equal 'text/html', response.content_type.to_s
end
@@ -101,7 +101,7 @@ module ShowExceptions
@app.instance_variable_set(:@exceptions_app, nil)
$stderr = StringIO.new
- get '/', {}, 'HTTP_ACCEPT' => 'text/json'
+ get '/', headers: { 'HTTP_ACCEPT' => 'text/json' }
assert_response :internal_server_error
assert_equal 'text/plain', response.content_type.to_s
ensure
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index 9d7abd5e94..ca854040b7 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -1,61 +1,67 @@
require 'abstract_unit'
require 'controller/fake_controllers'
require 'active_support/json/decoding'
+require 'rails/engine'
class TestCaseTest < ActionController::TestCase
class TestController < ActionController::Base
def no_op
- render :text => 'dummy'
+ render text: 'dummy'
end
def set_flash
flash["test"] = ">#{flash["test"]}<"
+ render text: 'ignore me'
+ end
+
+ def delete_flash
+ flash.delete("test")
render :text => 'ignore me'
end
def set_flash_now
flash.now["test_now"] = ">#{flash["test_now"]}<"
- render :text => 'ignore me'
+ render text: 'ignore me'
end
def set_session
session['string'] = 'A wonder'
session[:symbol] = 'it works'
- render :text => 'Success'
+ render text: 'Success'
end
def reset_the_session
reset_session
- render :text => 'ignore me'
+ render text: 'ignore me'
end
def render_raw_post
raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
- render :text => request.raw_post
+ render text: request.raw_post
end
def render_body
- render :text => request.body.read
+ render text: request.body.read
end
def test_params
- render :text => params.inspect
+ render text: params.inspect
end
def test_uri
- render :text => request.fullpath
+ render text: request.fullpath
end
def test_format
- render :text => request.format
+ render text: request.format
end
def test_query_string
- render :text => request.query_string
+ render text: request.query_string
end
def test_protocol
- render :text => request.protocol
+ render text: request.protocol
end
def test_headers
@@ -63,7 +69,7 @@ class TestCaseTest < ActionController::TestCase
end
def test_html_output
- render :text => <<HTML
+ render text: <<HTML
<html>
<body>
<a href="/"><img src="/images/button.png" /></a>
@@ -85,7 +91,7 @@ HTML
def test_xml_output
response.content_type = "application/xml"
- render :text => <<XML
+ render text: <<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<area>area is an empty tag in HTML, raising an error if not in xml mode</area>
@@ -94,15 +100,15 @@ XML
end
def test_only_one_param
- render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
+ render text: (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
end
def test_remote_addr
- render :text => (request.remote_addr || "not specified")
+ render text: (request.remote_addr || "not specified")
end
def test_file_upload
- render :text => params[:file].size
+ render text: params[:file].size
end
def test_send_file
@@ -110,32 +116,40 @@ XML
end
def redirect_to_same_controller
- redirect_to :controller => 'test', :action => 'test_uri', :id => 5
+ redirect_to controller: 'test', action: 'test_uri', id: 5
end
def redirect_to_different_controller
- redirect_to :controller => 'fail', :id => 5
+ redirect_to controller: 'fail', id: 5
end
def create
- head :created, :location => 'created resource'
+ head :created, location: 'created resource'
end
def delete_cookie
cookies.delete("foo")
- render :nothing => true
+ render nothing: true
end
def test_assigns
@foo = "foo"
- @foo_hash = {:foo => :bar}
- render :nothing => true
+ @foo_hash = { foo: :bar }
+ render nothing: true
+ end
+
+ def test_without_body
+ render html: '<div class="foo"></div>'.html_safe
+ end
+
+ def test_with_body
+ render html: '<body class="foo"></body>'.html_safe
end
private
def generate_url(opts)
- url_for(opts.merge(:action => "test_uri"))
+ url_for(opts.merge(action: "test_uri"))
end
end
@@ -155,7 +169,7 @@ XML
class ViewAssignsController < ActionController::Base
def test_assigns
@foo = "foo"
- render :nothing => true
+ render nothing: true
end
def view_assigns
@@ -179,6 +193,19 @@ XML
end
end
+ def test_assert_select_without_body
+ get :test_without_body
+
+ assert_select 'body', 0
+ assert_select 'div.foo'
+ end
+
+ def test_assert_select_with_body
+ get :test_with_body
+
+ assert_select 'body.foo'
+ end
+
def test_url_options_reset
@controller = DefaultUrlOptionsCachingController.new
get :test_url_options_reset
@@ -187,32 +214,50 @@ XML
end
def test_raw_post_handling
- params = Hash[:page, {:name => 'page name'}, 'some key', 123]
- post :render_raw_post, params.dup
+ params = Hash[:page, { name: 'page name' }, 'some key', 123]
+ post :render_raw_post, params: params.dup
assert_equal params.to_query, @response.body
end
def test_body_stream
- params = Hash[:page, { :name => 'page name' }, 'some key', 123]
+ params = Hash[:page, { name: 'page name' }, 'some key', 123]
+
+ post :render_body, params: params.dup
+
+ assert_equal params.to_query, @response.body
+ end
+
+ def test_deprecated_body_stream
+ params = Hash[:page, { name: 'page name' }, 'some key', 123]
- post :render_body, params.dup
+ assert_deprecated { post :render_body, params.dup }
assert_equal params.to_query, @response.body
end
def test_document_body_and_params_with_post
- post :test_params, :id => 1
- assert_equal("{\"id\"=>\"1\", \"controller\"=>\"test_case_test/test\", \"action\"=>\"test_params\"}", @response.body)
+ post :test_params, params: { id: 1 }
+ assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
end
def test_document_body_with_post
- post :render_body, "document body"
+ post :render_body, body: "document body"
+ assert_equal "document body", @response.body
+ end
+
+ def test_deprecated_document_body_with_post
+ assert_deprecated { post :render_body, "document body" }
assert_equal "document body", @response.body
end
def test_document_body_with_put
- put :render_body, "document body"
+ put :render_body, body: "document body"
+ assert_equal "document body", @response.body
+ end
+
+ def test_deprecated_document_body_with_put
+ assert_deprecated { put :render_body, "document body" }
assert_equal "document body", @response.body
end
@@ -221,25 +266,42 @@ XML
assert_equal 200, @response.status
end
- def test_head_params_as_string
- assert_raise(NoMethodError) { head :test_params, "document body", :id => 10 }
- end
-
def test_process_without_flash
process :set_flash
assert_equal '><', flash['test']
end
+ def test_deprecated_process_with_flash
+ assert_deprecated { process :set_flash, "GET", nil, nil, { "test" => "value" } }
+ assert_equal '>value<', flash['test']
+ end
+
def test_process_with_flash
- process :set_flash, "GET", nil, nil, { "test" => "value" }
+ process :set_flash,
+ method: "GET",
+ flash: { "test" => "value" }
assert_equal '>value<', flash['test']
end
+ def test_deprecated_process_with_flash_now
+ assert_deprecated { process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" } }
+ assert_equal '>value_now<', flash['test_now']
+ end
+
def test_process_with_flash_now
- process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" }
+ process :set_flash_now,
+ method: "GET",
+ flash: { "test_now" => "value_now" }
assert_equal '>value_now<', flash['test_now']
end
+ def test_process_delete_flash
+ process :set_flash
+ process :delete_flash
+ assert_empty flash
+ assert_empty session
+ end
+
def test_process_with_session
process :set_session
assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
@@ -249,22 +311,48 @@ XML
end
def test_process_with_session_arg
- process :no_op, "GET", nil, { 'string' => 'value1', :symbol => 'value2' }
+ assert_deprecated { process :no_op, "GET", nil, { 'string' => 'value1', symbol: 'value2' } }
+ assert_equal 'value1', session['string']
+ assert_equal 'value1', session[:string]
+ assert_equal 'value2', session['symbol']
+ assert_equal 'value2', session[:symbol]
+ end
+
+ def test_process_with_session_kwarg
+ process :no_op, method: "GET", session: { 'string' => 'value1', symbol: 'value2' }
assert_equal 'value1', session['string']
assert_equal 'value1', session[:string]
assert_equal 'value2', session['symbol']
assert_equal 'value2', session[:symbol]
end
+ def test_deprecated_process_merges_session_arg
+ session[:foo] = 'bar'
+ assert_deprecated {
+ get :no_op, nil, { bar: 'baz' }
+ }
+ assert_equal 'bar', session[:foo]
+ assert_equal 'baz', session[:bar]
+ end
+
def test_process_merges_session_arg
session[:foo] = 'bar'
- get :no_op, nil, { :bar => 'baz' }
+ get :no_op, session: { bar: 'baz' }
assert_equal 'bar', session[:foo]
assert_equal 'baz', session[:bar]
end
+ def test_deprecated_merged_session_arg_is_retained_across_requests
+ assert_deprecated {
+ get :no_op, nil, { foo: 'bar' }
+ }
+ assert_equal 'bar', session[:foo]
+ get :no_op
+ assert_equal 'bar', session[:foo]
+ end
+
def test_merged_session_arg_is_retained_across_requests
- get :no_op, nil, { :foo => 'bar' }
+ get :no_op, session: { foo: 'bar' }
assert_equal 'bar', session[:foo]
get :no_op
assert_equal 'bar', session[:foo]
@@ -272,7 +360,7 @@ XML
def test_process_overwrites_existing_session_arg
session[:foo] = 'bar'
- get :no_op, nil, { :foo => 'baz' }
+ get :no_op, session: { foo: 'baz' }
assert_equal 'baz', session[:foo]
end
@@ -299,19 +387,40 @@ XML
assert_equal "/test_case_test/test/test_uri", @response.body
end
+ def test_process_with_symbol_method
+ process :test_uri, method: :get
+ assert_equal "/test_case_test/test/test_uri", @response.body
+ end
+
+ def test_deprecated_process_with_request_uri_with_params
+ assert_deprecated { process :test_uri, "GET", id: 7 }
+ assert_equal "/test_case_test/test/test_uri/7", @response.body
+ end
+
def test_process_with_request_uri_with_params
- process :test_uri, "GET", :id => 7
+ process :test_uri,
+ method: "GET",
+ params: { id: 7 }
+
assert_equal "/test_case_test/test/test_uri/7", @response.body
end
+ def test_deprecated_process_with_request_uri_with_params_with_explicit_uri
+ @request.env['PATH_INFO'] = "/explicit/uri"
+ assert_deprecated { process :test_uri, "GET", id: 7 }
+ assert_equal "/explicit/uri", @response.body
+ end
+
def test_process_with_request_uri_with_params_with_explicit_uri
@request.env['PATH_INFO'] = "/explicit/uri"
- process :test_uri, "GET", :id => 7
+ process :test_uri, method: "GET", params: { id: 7 }
assert_equal "/explicit/uri", @response.body
end
def test_process_with_query_string
- process :test_query_string, "GET", :q => 'test'
+ process :test_query_string,
+ method: "GET",
+ params: { q: 'test' }
assert_equal "q=test", @response.body
end
@@ -323,9 +432,9 @@ XML
end
def test_multiple_calls
- process :test_only_one_param, "GET", :left => true
+ process :test_only_one_param, method: "GET", params: { left: true }
assert_equal "OK", @response.body
- process :test_only_one_param, "GET", :right => true
+ process :test_only_one_param, method: "GET", params: { right: true }
assert_equal "OK", @response.body
end
@@ -340,7 +449,7 @@ XML
assert_equal "foo", assigns["foo"]
# but the assigned variable should not have its own keys stringified
- expected_hash = { :foo => :bar }
+ expected_hash = { foo: :bar }
assert_equal expected_hash, assigns(:foo_hash)
end
@@ -368,21 +477,21 @@ XML
end
def test_assert_generates
- assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
- assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action"}
- assert_generates 'controller/action/5', {:controller => "controller", :action => "action", :id => "5", :name => "bob"}, {}, {:name => "bob"}
- assert_generates 'controller/action/7', {:id => "7", :name => "bob"}, {:controller => "controller", :action => "action"}, {:name => "bob"}
- assert_generates 'controller/action/7', {:id => "7"}, {:controller => "controller", :action => "action", :name => "bob"}, {}
+ assert_generates 'controller/action/5', controller: 'controller', action: 'action', id: '5'
+ assert_generates 'controller/action/7', { id: "7" }, { controller: "controller", action: "action" }
+ assert_generates 'controller/action/5', { controller: "controller", action: "action", id: "5", name: "bob" }, {}, { name: "bob" }
+ assert_generates 'controller/action/7', { id: "7", name: "bob" }, { controller: "controller", action: "action" }, { name: "bob" }
+ assert_generates 'controller/action/7', { id: "7" }, { controller: "controller", action: "action", name: "bob" }, {}
end
def test_assert_routing
- assert_routing 'content', :controller => 'content', :action => 'index'
+ assert_routing 'content', controller: 'content', action: 'index'
end
def test_assert_routing_with_method
with_routing do |set|
set.draw { resources(:content) }
- assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
+ assert_routing({ method: 'post', path: 'content' }, { controller: 'content', action: 'create' })
end
end
@@ -394,29 +503,75 @@ XML
end
end
- assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
+ assert_routing 'admin/user', controller: 'admin/user', action: 'index'
end
end
def test_assert_routing_with_glob
with_routing do |set|
set.draw { get('*path' => "pages#show") }
- assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' })
+ assert_routing('/company/about', { controller: 'pages', action: 'show', path: 'company/about' })
end
end
+ def test_deprecated_params_passing
+ assert_deprecated {
+ get :test_params, page: { name: "Page name", month: '4', year: '2004', day: '6' }
+ }
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {
+ 'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'page' => { 'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6' }
+ },
+ parsed_params
+ )
+ end
+
def test_params_passing
- get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
+ get :test_params, params: {
+ page: {
+ name: "Page name",
+ month: '4',
+ year: '2004',
+ day: '6'
+ }
+ }
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {
+ 'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'page' => { 'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6' }
+ },
+ parsed_params
+ )
+ end
+
+ def test_kwarg_params_passing_with_session_and_flash
+ get :test_params, params: {
+ page: {
+ name: "Page name",
+ month: '4',
+ year: '2004',
+ day: '6'
+ }
+ }, session: { 'foo' => 'bar' }, flash: { notice: 'created' }
+
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
parsed_params
)
+
+ assert_equal 'bar', session[:foo]
+ assert_equal 'created', flash[:notice]
end
def test_params_passing_with_fixnums
- get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6}
+ get :test_params, params: {
+ page: { name: "Page name", month: 4, year: 2004, day: 6 }
+ }
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -426,7 +581,7 @@ XML
end
def test_params_passing_with_fixnums_when_not_html_request
- get :test_params, :format => 'json', :count => 999
+ get :test_params, params: { format: 'json', count: 999 }
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -436,7 +591,17 @@ XML
end
def test_params_passing_path_parameter_is_string_when_not_html_request
- get :test_params, :format => 'json', :id => 1
+ get :test_params, params: { format: 'json', id: 1 }
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_case_test/test', 'action' => 'test_params',
+ 'format' => 'json', 'id' => '1' },
+ parsed_params
+ )
+ end
+
+ def test_deprecated_params_passing_path_parameter_is_string_when_not_html_request
+ assert_deprecated { get :test_params, format: 'json', id: 1 }
parsed_params = eval(@response.body)
assert_equal(
{'controller' => 'test_case_test/test', 'action' => 'test_params',
@@ -447,7 +612,9 @@ XML
def test_params_passing_with_frozen_values
assert_nothing_raised do
- get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze, :deepfreeze => { :frozen => 'icy'.freeze }.freeze
+ get :test_params, params: {
+ frozen: 'icy'.freeze, frozens: ['icy'.freeze].freeze, deepfreeze: { frozen: 'icy'.freeze }.freeze
+ }
end
parsed_params = eval(@response.body)
assert_equal(
@@ -458,8 +625,8 @@ XML
end
def test_params_passing_doesnt_modify_in_place
- page = {:name => "Page name", :month => 4, :year => 2004, :day => 6}
- get :test_params, :page => page
+ page = { name: "Page name", month: 4, year: 2004, day: 6 }
+ get :test_params, params: { page: page }
assert_equal 2004, page[:year]
end
@@ -482,25 +649,32 @@ XML
end
def test_id_converted_to_string
- get :test_params, :id => 20, :foo => Object.new
+ get :test_params, params: {
+ id: 20, foo: Object.new
+ }
+ assert_kind_of String, @request.path_parameters[:id]
+ end
+
+ def test_deprecared_id_converted_to_string
+ assert_deprecated { get :test_params, id: 20, foo: Object.new}
assert_kind_of String, @request.path_parameters[:id]
end
def test_array_path_parameter_handled_properly
with_routing do |set|
set.draw do
- get 'file/*path', :to => 'test_case_test/test#test_params'
+ get 'file/*path', to: 'test_case_test/test#test_params'
get ':controller/:action'
end
- get :test_params, :path => ['hello', 'world']
+ get :test_params, params: { path: ['hello', 'world'] }
assert_equal ['hello', 'world'], @request.path_parameters[:path]
assert_equal 'hello/world', @request.path_parameters[:path].to_param
end
end
def test_assert_realistic_path_parameters
- get :test_params, :id => 20, :foo => Object.new
+ get :test_params, params: { id: 20, foo: Object.new }
# All elements of path_parameters should use Symbol keys
@request.path_parameters.each_key do |key|
@@ -532,19 +706,57 @@ XML
end
def test_header_properly_reset_after_remote_http_request
- xhr :get, :test_params
+ get :test_params, xhr: true
assert_nil @request.env['HTTP_X_REQUESTED_WITH']
assert_nil @request.env['HTTP_ACCEPT']
end
+ def test_deprecated_xhr_with_params
+ assert_deprecated { xhr :get, :test_params, params: { id: 1 } }
+
+ assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ end
+
+ def test_xhr_with_params
+ get :test_params, params: { id: 1 }, xhr: true
+
+ assert_equal(%({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}), @response.body)
+ end
+
+ def test_xhr_with_session
+ get :set_session, xhr: true
+
+ assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
+ assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
+ end
+
+ def test_deprecated_xhr_with_session
+ assert_deprecated { xhr :get, :set_session }
+
+ assert_equal 'A wonder', session['string'], "A value stored in the session should be available by string key"
+ assert_equal 'A wonder', session[:string], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session['symbol'], "Test session hash should allow indifferent access"
+ assert_equal 'it works', session[:symbol], "Test session hash should allow indifferent access"
+ end
+
def test_header_properly_reset_after_get_request
get :test_params
@request.recycle!
assert_nil @request.instance_variable_get("@request_method")
end
+ def test_deprecated_params_reset_between_post_requests
+ assert_deprecated { post :no_op, foo: "bar" }
+ assert_equal "bar", @request.params[:foo]
+
+ post :no_op
+ assert @request.params[:foo].blank?
+ end
+
def test_params_reset_between_post_requests
- post :no_op, :foo => "bar"
+ post :no_op, params: { foo: "bar" }
assert_equal "bar", @request.params[:foo]
post :no_op
@@ -552,15 +764,15 @@ XML
end
def test_filtered_parameters_reset_between_requests
- get :no_op, :foo => "bar"
+ get :no_op, params: { foo: "bar" }
assert_equal "bar", @request.filtered_parameters[:foo]
- get :no_op, :foo => "baz"
+ get :no_op, params: { foo: "baz" }
assert_equal "baz", @request.filtered_parameters[:foo]
end
def test_path_params_reset_between_request
- get :test_params, :id => "foo"
+ get :test_params, params: { id: "foo" }
assert_equal "foo", @request.path_parameters[:id]
get :test_params
@@ -581,19 +793,38 @@ XML
end
def test_request_format
- get :test_format, :format => 'html'
+ get :test_format, params: { format: 'html' }
assert_equal 'text/html', @response.body
- get :test_format, :format => 'json'
+ get :test_format, params: { format: 'json' }
assert_equal 'application/json', @response.body
- get :test_format, :format => 'xml'
+ get :test_format, params: { format: 'xml' }
assert_equal 'application/xml', @response.body
get :test_format
assert_equal 'text/html', @response.body
end
+ def test_request_format_kwarg
+ get :test_format, format: 'html'
+ assert_equal 'text/html', @response.body
+
+ get :test_format, format: 'json'
+ assert_equal 'application/json', @response.body
+
+ get :test_format, format: 'xml'
+ assert_equal 'application/xml', @response.body
+
+ get :test_format
+ assert_equal 'text/html', @response.body
+ end
+
+ def test_request_format_kwarg_overrides_params
+ get :test_format, format: 'json', params: { format: 'html' }
+ assert_equal 'application/json', @response.body
+ end
+
def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
cookies['foo'] = 'bar'
get :no_op
@@ -678,7 +909,10 @@ XML
end
def test_fixture_file_upload
- post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
+ post :test_file_upload,
+ params: {
+ file: fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
+ }
assert_equal '159528', @response.body
end
@@ -694,10 +928,21 @@ XML
assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
end
+ def test_deprecated_action_dispatch_uploaded_file_upload
+ filename = 'mona_lisa.jpg'
+ path = "#{FILES_DIR}/#{filename}"
+ assert_deprecated {
+ post :test_file_upload, file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ }
+ assert_equal '159528', @response.body
+ end
+
def test_action_dispatch_uploaded_file_upload
filename = 'mona_lisa.jpg'
path = "#{FILES_DIR}/#{filename}"
- post :test_file_upload, :file => ActionDispatch::Http::UploadedFile.new(:filename => path, :type => "image/jpg", :tempfile => File.open(path))
+ post :test_file_upload, params: {
+ file: ActionDispatch::Http::UploadedFile.new(filename: path, type: "image/jpg", tempfile: File.open(path))
+ }
assert_equal '159528', @response.body
end
@@ -720,6 +965,44 @@ XML
end
end
+module EngineControllerTests
+ class Engine < ::Rails::Engine
+ isolate_namespace EngineControllerTests
+
+ routes.draw do
+ get '/' => 'bar#index'
+ end
+ end
+
+ class BarController < ActionController::Base
+ def index
+ render text: 'bar'
+ end
+ end
+
+ class BarControllerTest < ActionController::TestCase
+ tests BarController
+
+ def test_engine_controller_route
+ get :index
+ assert_equal @response.body, 'bar'
+ end
+ end
+
+ class BarControllerTestWithExplicitRouteSet < ActionController::TestCase
+ tests BarController
+
+ def setup
+ @routes = Engine.routes
+ end
+
+ def test_engine_controller_route
+ get :index
+ assert_equal @response.body, 'bar'
+ end
+ end
+end
+
class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
@@ -770,7 +1053,7 @@ class NamedRoutesControllerTest < ActionController::TestCase
with_routing do |set|
set.draw { resources :contents }
assert_equal 'http://test.host/contents/new', new_content_url
- assert_equal 'http://test.host/contents/1', content_url(:id => 1)
+ assert_equal 'http://test.host/contents/1', content_url(id: 1)
end
end
end
@@ -779,7 +1062,7 @@ class AnonymousControllerTest < ActionController::TestCase
def setup
@controller = Class.new(ActionController::Base) do
def index
- render :text => params[:controller]
+ render text: params[:controller]
end
end.new
@@ -800,29 +1083,29 @@ class RoutingDefaultsTest < ActionController::TestCase
def setup
@controller = Class.new(ActionController::Base) do
def post
- render :text => request.fullpath
+ render text: request.fullpath
end
def project
- render :text => request.fullpath
+ render text: request.fullpath
end
end.new
@routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
- get '/posts/:id', :to => 'anonymous#post', :bucket_type => 'post'
- get '/projects/:id', :to => 'anonymous#project', :defaults => { :bucket_type => 'project' }
+ get '/posts/:id', to: 'anonymous#post', bucket_type: 'post'
+ get '/projects/:id', to: 'anonymous#project', defaults: { bucket_type: 'project' }
end
end
end
def test_route_option_can_be_passed_via_process
- get :post, :id => 1, :bucket_type => 'post'
+ get :post, params: { id: 1, bucket_type: 'post'}
assert_equal '/posts/1', @response.body
end
def test_route_default_is_not_required_for_building_request_uri
- get :project, :id => 2
+ get :project, params: { id: 2 }
assert_equal '/projects/2', @response.body
end
end
diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb
index 24a09222b1..0e4c2b7c32 100644
--- a/actionpack/test/controller/url_for_integration_test.rb
+++ b/actionpack/test/controller/url_for_integration_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'abstract_unit'
require 'controller/fake_controllers'
require 'active_support/core_ext/object/with_options'
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 969129d9ba..0ffa2d2a03 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -25,8 +25,7 @@ module AbstractController
path = klass.new.fun_path({:controller => :articles,
:baz => "baz",
- :zot => "zot",
- :only_path => true })
+ :zot => "zot"})
# :bar key isn't provided
assert_equal '/foo/zot', path
end
@@ -55,6 +54,20 @@ module AbstractController
)
end
+ def test_nil_anchor
+ assert_equal(
+ '/c/a',
+ W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: nil)
+ )
+ end
+
+ def test_false_anchor
+ assert_equal(
+ '/c/a',
+ W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: false)
+ )
+ end
+
def test_anchor_should_call_to_param
assert_equal('/c/a#anchor',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor'))
@@ -277,6 +290,13 @@ module AbstractController
end
end
+ def test_using_nil_script_name_properly_concats_with_original_script_name
+ add_host!
+ assert_equal('https://www.basecamphq.com/subdir/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https', :script_name => nil, :original_script_name => '/subdir')
+ )
+ end
+
def test_only_path
with_routing do |set|
set.draw do
@@ -291,7 +311,7 @@ module AbstractController
assert_equal '/brave/new/world',
controller.url_for(:controller => 'brave', :action => 'new', :id => 'world', :only_path => true)
- assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused', :only_path => true))
+ assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused'))
assert_equal("/home/sweet/home/alabama", controller.home_path('alabama'))
end
end
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index d80b0e2da0..21fa670bb6 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -35,7 +35,9 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_post_json
with_test_route_set do
- post "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
+ post "/",
+ params: '{"entry":{"summary":"content..."}}',
+ headers: { 'CONTENT_TYPE' => 'application/json' }
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
@@ -45,7 +47,9 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_put_json
with_test_route_set do
- put "/", '{"entry":{"summary":"content..."}}', 'CONTENT_TYPE' => 'application/json'
+ put "/",
+ params: '{"entry":{"summary":"content..."}}',
+ headers: { 'CONTENT_TYPE' => 'application/json' }
assert_equal 'entry', @controller.response.body
assert @controller.params.has_key?(:entry)
@@ -56,8 +60,9 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_register_and_use_json_simple
with_test_route_set do
with_params_parsers Mime::JSON => Proc.new { |data| ActiveSupport::JSON.decode(data)['request'].with_indifferent_access } do
- post "/", '{"request":{"summary":"content...","title":"JSON"}}',
- 'CONTENT_TYPE' => 'application/json'
+ post "/",
+ params: '{"request":{"summary":"content...","title":"JSON"}}',
+ headers: { 'CONTENT_TYPE' => 'application/json' }
assert_equal 'summary, title', @controller.response.body
assert @controller.params.has_key?(:summary)
@@ -70,19 +75,33 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_use_json_with_empty_request
with_test_route_set do
- assert_nothing_raised { post "/", "", 'CONTENT_TYPE' => 'application/json' }
+ assert_nothing_raised { post "/", headers: { 'CONTENT_TYPE' => 'application/json' } }
assert_equal '', @controller.response.body
end
end
def test_dasherized_keys_as_json
with_test_route_set do
- post "/?full=1", '{"first-key":{"sub-key":"..."}}', 'CONTENT_TYPE' => 'application/json'
+ post "/?full=1",
+ params: '{"first-key":{"sub-key":"..."}}',
+ headers: { 'CONTENT_TYPE' => 'application/json' }
assert_equal 'action, controller, first-key(sub-key), full', @controller.response.body
assert_equal "...", @controller.params['first-key']['sub-key']
end
end
+ def test_parsing_json_doesnot_rescue_exception
+ with_test_route_set do
+ with_params_parsers Mime::JSON => Proc.new { |data| raise Interrupt } do
+ assert_raises(Interrupt) do
+ post "/",
+ params: '{"title":"JSON"}}',
+ headers: { 'CONTENT_TYPE' => 'application/json' }
+ end
+ end
+ end
+ end
+
private
def with_params_parsers(parsers = {})
old_session = @integration_session
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 7dc6c37522..6223a52a76 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -1,12 +1,5 @@
require 'abstract_unit'
-
-begin
- require 'openssl'
- OpenSSL::PKCS5
-rescue LoadError, NameError
- $stderr.puts "Skipping KeyGenerator test: broken OpenSSL install"
-else
-
+require 'openssl'
require 'active_support/key_generator'
require 'active_support/message_verifier'
@@ -152,11 +145,21 @@ class CookiesTest < ActionController::TestCase
head :ok
end
+ def set_cookie_with_domain_all_as_string
+ cookies[:user_name] = {:value => "rizwanreza", :domain => 'all'}
+ head :ok
+ end
+
def delete_cookie_with_domain
cookies.delete(:user_name, :domain => :all)
head :ok
end
+ def delete_cookie_with_domain_all_as_string
+ cookies.delete(:user_name, :domain => 'all')
+ head :ok
+ end
+
def set_cookie_with_domain_and_tld
cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2}
head :ok
@@ -494,7 +497,7 @@ class CookiesTest < ActionController::TestCase
assert_nil @response.cookies["user_id"]
end
- def test_accessing_nonexistant_signed_cookie_should_not_raise_an_invalid_signature
+ def test_accessing_nonexistent_signed_cookie_should_not_raise_an_invalid_signature
get :set_signed_cookie
assert_nil @controller.send(:cookies).signed[:non_existant_attribute]
end
@@ -612,7 +615,7 @@ class CookiesTest < ActionController::TestCase
assert_nil @response.cookies["foo"]
end
- def test_accessing_nonexistant_encrypted_cookie_should_not_raise_invalid_message
+ def test_accessing_nonexistent_encrypted_cookie_should_not_raise_invalid_message
get :set_encrypted_cookie
assert_nil @controller.send(:cookies).encrypted[:non_existant_attribute]
end
@@ -984,6 +987,13 @@ class CookiesTest < ActionController::TestCase
assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
end
+ def test_cookie_with_all_domain_option_using_a_non_standard_2_letter_tld
+ @request.host = "admin.lvh.me"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.lvh.me; path=/"
+ end
+
def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length
@request.host = "nextangle.local:3000"
get :set_cookie_with_domain_and_tld
@@ -1155,5 +1165,3 @@ class CookiesTest < ActionController::TestCase
end
end
end
-
-end
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index 0add9fa3b0..7921f05688 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -19,6 +19,10 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
@closed = true
end
+ def method_that_raises
+ raise StandardError.new 'error in framework'
+ end
+
def call(env)
env['action_dispatch.show_detailed_exceptions'] = @detailed
req = ActionDispatch::Request.new(env)
@@ -39,6 +43,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
raise ActionController::InvalidAuthenticityToken
when "/not_found_original_exception"
raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
+ when "/missing_template"
+ raise ActionView::MissingTemplate.new(%w(foo), 'foo/index', %w(foo), false, 'mailer')
when "/bad_request"
raise ActionController::BadRequest
when "/missing_keys"
@@ -57,7 +63,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
{})
raise ActionView::Template::Error.new(template, e)
end
-
+ when "/framework_raises"
+ method_that_raises
else
raise "puke!"
end
@@ -79,21 +86,21 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test 'skip diagnosis if not showing detailed exceptions' do
@app = ProductionApp
assert_raise RuntimeError do
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
end
end
test 'skip diagnosis if not showing exceptions' do
@app = DevelopmentApp
assert_raise RuntimeError do
- get "/", {}, {'action_dispatch.show_exceptions' => false}
+ get "/", headers: { 'action_dispatch.show_exceptions' => false }
end
end
test 'raise an exception on cascade pass' do
@app = ProductionApp
assert_raise ActionController::RoutingError do
- get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ get "/pass", headers: { 'action_dispatch.show_exceptions' => true }
end
end
@@ -101,44 +108,53 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
boomer = Boomer.new(false)
@app = ActionDispatch::DebugExceptions.new(boomer)
assert_raise ActionController::RoutingError do
- get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ get "/pass", headers: { 'action_dispatch.show_exceptions' => true }
end
assert boomer.closed, "Expected to close the response body"
end
test 'displays routes in a table when a RoutingError occurs' do
@app = DevelopmentApp
- get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ get "/pass", headers: { 'action_dispatch.show_exceptions' => true }
routing_table = body[/route_table.*<.table>/m]
assert_match '/:controller(/:action)(.:format)', routing_table
assert_match ':controller#:action', routing_table
assert_no_match '&lt;|&gt;', routing_table, "there should not be escaped html in the output"
end
+ test 'displays request and response info when a RoutingError occurs' do
+ @app = DevelopmentApp
+
+ get "/pass", headers: { 'action_dispatch.show_exceptions' => true }
+
+ assert_select 'h2', /Request/
+ assert_select 'h2', /Response/
+ end
+
test "rescue with diagnostics message" do
@app = DevelopmentApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 500
assert_match(/puke/, body)
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_match(/#{AbstractController::ActionNotFound.name}/, body)
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ get "/method_not_allowed", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 405
assert_match(/ActionController::MethodNotAllowed/, body)
- get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
+ get "/unknown_http_method", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 405
assert_match(/ActionController::UnknownHttpMethod/, body)
- get "/bad_request", {}, {'action_dispatch.show_exceptions' => true}
+ get "/bad_request", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 400
assert_match(/ActionController::BadRequest/, body)
- get "/parameter_missing", {}, {'action_dispatch.show_exceptions' => true}
+ get "/parameter_missing", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 400
assert_match(/ActionController::ParameterMissing/, body)
end
@@ -147,38 +163,38 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
@app = DevelopmentApp
xhr_request_env = {'action_dispatch.show_exceptions' => true, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'}
- get "/", {}, xhr_request_env
+ get "/", headers: xhr_request_env
assert_response 500
assert_no_match(/<header>/, body)
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
assert_match(/RuntimeError\npuke/, body)
- get "/not_found", {}, xhr_request_env
+ get "/not_found", headers: xhr_request_env
assert_response 404
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
assert_match(/#{AbstractController::ActionNotFound.name}/, body)
- get "/method_not_allowed", {}, xhr_request_env
+ get "/method_not_allowed", headers: xhr_request_env
assert_response 405
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
assert_match(/ActionController::MethodNotAllowed/, body)
- get "/unknown_http_method", {}, xhr_request_env
+ get "/unknown_http_method", headers: xhr_request_env
assert_response 405
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
assert_match(/ActionController::UnknownHttpMethod/, body)
- get "/bad_request", {}, xhr_request_env
+ get "/bad_request", headers: xhr_request_env
assert_response 400
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
assert_match(/ActionController::BadRequest/, body)
- get "/parameter_missing", {}, xhr_request_env
+ get "/parameter_missing", headers: xhr_request_env
assert_response 400
assert_no_match(/<body>/, body)
assert_equal "text/plain", response.content_type
@@ -188,8 +204,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test "does not show filtered parameters" do
@app = DevelopmentApp
- get "/", {"foo"=>"bar"}, {'action_dispatch.show_exceptions' => true,
- 'action_dispatch.parameter_filter' => [:foo]}
+ get "/", params: { "foo"=>"bar" }, headers: { 'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.parameter_filter' => [:foo] }
assert_response 500
assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
end
@@ -197,7 +213,7 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test "show registered original exception for wrapped exceptions" do
@app = DevelopmentApp
- get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found_original_exception", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_match(/AbstractController::ActionNotFound/, body)
end
@@ -205,7 +221,7 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test "named urls missing keys raise 500 level error" do
@app = DevelopmentApp
- get "/missing_keys", {}, {'action_dispatch.show_exceptions' => true}
+ get "/missing_keys", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 500
assert_match(/ActionController::UrlGenerationError/, body)
@@ -213,7 +229,7 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test "show the controller name in the diagnostics template when controller name is present" do
@app = DevelopmentApp
- get("/runtime_error", {}, {
+ get("/runtime_error", headers: {
'action_dispatch.show_exceptions' => true,
'action_dispatch.request.parameters' => {
'action' => 'show',
@@ -225,24 +241,47 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
assert_match(/RuntimeError\n\s+in FeaturedTileController/, body)
end
+ test "show formatted params" do
+ @app = DevelopmentApp
+
+ params = {
+ 'id' => 'unknown',
+ 'someparam' => {
+ 'foo' => 'bar',
+ 'abc' => 'goo'
+ }
+ }
+
+ get("/runtime_error", headers: {
+ 'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.request.parameters' => {
+ 'action' => 'show',
+ 'controller' => 'featured_tile'
+ }.merge(params)
+ })
+ assert_response 500
+
+ assert_includes(body, CGI.escapeHTML(PP.pp(params, "", 200)))
+ end
+
test "sets the HTTP charset parameter" do
@app = DevelopmentApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
end
test 'uses logger from env' do
@app = DevelopmentApp
output = StringIO.new
- get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output) }
assert_match(/puke/, output.rewind && output.read)
end
test 'uses backtrace cleaner from env' do
@app = DevelopmentApp
cleaner = stub(:clean => ['passed backtrace cleaner'])
- get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner }
assert_match(/passed backtrace cleaner/, body)
end
@@ -255,14 +294,14 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
'action_dispatch.logger' => Logger.new(output),
'action_dispatch.backtrace_cleaner' => backtrace_cleaner}
- get "/", {}, env
+ get "/", headers: env
assert_operator((output.rewind && output.read).lines.count, :>, 10)
end
test 'display backtrace when error type is SyntaxError' do
@app = DevelopmentApp
- get '/original_syntax_error', {}, {'action_dispatch.backtrace_cleaner' => ActiveSupport::BacktraceCleaner.new}
+ get '/original_syntax_error', headers: { 'action_dispatch.backtrace_cleaner' => ActiveSupport::BacktraceCleaner.new }
assert_response 500
assert_select '#Application-Trace' do
@@ -270,14 +309,65 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
end
end
+ test 'display backtrace on template missing errors' do
+ @app = DevelopmentApp
+
+ get "/missing_template"
+
+ assert_select "header h1", /Template is missing/
+
+ assert_select "#container h2", /^Missing template/
+
+ assert_select '#Application-Trace'
+ assert_select '#Framework-Trace'
+ assert_select '#Full-Trace'
+
+ assert_select 'h2', /Request/
+ end
+
test 'display backtrace when error type is SyntaxError wrapped by ActionView::Template::Error' do
@app = DevelopmentApp
- get '/syntax_error_into_view', {}, {'action_dispatch.backtrace_cleaner' => ActiveSupport::BacktraceCleaner.new}
+ get '/syntax_error_into_view', headers: { 'action_dispatch.backtrace_cleaner' => ActiveSupport::BacktraceCleaner.new }
assert_response 500
assert_select '#Application-Trace' do
assert_select 'pre code', /\(eval\):1: syntax error, unexpected/
end
end
+
+ test 'debug exceptions app shows user code that caused the error in source view' do
+ @app = DevelopmentApp
+ Rails.stubs(:root).returns(Pathname.new('.'))
+ cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc|
+ bc.add_silencer { |line| line =~ /method_that_raises/ }
+ bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} }
+ end
+
+ get '/framework_raises', headers: { 'action_dispatch.backtrace_cleaner' => cleaner }
+
+ # Assert correct error
+ assert_response 500
+ assert_select 'h2', /error in framework/
+
+ # assert source view line is the call to method_that_raises
+ assert_select 'div.source:not(.hidden)' do
+ assert_select 'pre .line.active', /method_that_raises/
+ end
+
+ # assert first source view (hidden) that throws the error
+ assert_select 'div.source:first' do
+ assert_select 'pre .line.active', /raise StandardError\.new/
+ end
+
+ # assert application trace refers to line that calls method_that_raises is first
+ assert_select '#Application-Trace' do
+ assert_select 'pre code a:first', %r{test/dispatch/debug_exceptions_test\.rb:\d+:in `call}
+ end
+
+ # assert framework trace that that threw the error is first
+ assert_select '#Framework-Trace' do
+ assert_select 'pre code a:first', /method_that_raises/
+ end
+ end
end
diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb
new file mode 100644
index 0000000000..7a29a7ff97
--- /dev/null
+++ b/actionpack/test/dispatch/exception_wrapper_test.rb
@@ -0,0 +1,114 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class ExceptionWrapperTest < ActionDispatch::IntegrationTest
+ class TestError < StandardError
+ attr_reader :backtrace
+
+ def initialize(*backtrace)
+ @backtrace = backtrace.flatten
+ end
+ end
+
+ class BadlyDefinedError < StandardError
+ def backtrace
+ nil
+ end
+ end
+
+ setup do
+ Rails.stubs(:root).returns(Pathname.new('.'))
+
+ cleaner = ActiveSupport::BacktraceCleaner.new
+ cleaner.add_silencer { |line| line !~ /^lib/ }
+
+ @environment = { 'action_dispatch.backtrace_cleaner' => cleaner }
+ end
+
+ test '#source_extracts fetches source fragments for every backtrace entry' do
+ exception = TestError.new("lib/file.rb:42:in `index'")
+ wrapper = ExceptionWrapper.new({}, exception)
+
+ wrapper.expects(:source_fragment).with('lib/file.rb', 42).returns('foo')
+
+ assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts
+ end
+
+ test '#source_extracts works with Windows paths' do
+ exc = TestError.new("c:/path/to/rails/app/controller.rb:27:in 'index':")
+
+ wrapper = ExceptionWrapper.new({}, exc)
+ wrapper.expects(:source_fragment).with('c:/path/to/rails/app/controller.rb', 27).returns('nothing')
+
+ assert_equal [ code: 'nothing', line_number: 27 ], wrapper.source_extracts
+ end
+
+ test '#source_extracts works with non standard backtrace' do
+ exc = TestError.new('invalid')
+
+ wrapper = ExceptionWrapper.new({}, exc)
+ wrapper.expects(:source_fragment).with('invalid', 0).returns('nothing')
+
+ assert_equal [ code: 'nothing', line_number: 0 ], wrapper.source_extracts
+ end
+
+ test '#application_trace returns traces only from the application' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal [ "lib/file.rb:42:in `index'" ], wrapper.application_trace
+ end
+
+ test '#application_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.application_trace
+ assert_equal [], nil_cleaner_wrapper.application_trace
+ end
+
+ test '#framework_trace returns traces outside the application' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal caller, wrapper.framework_trace
+ end
+
+ test '#framework_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.framework_trace
+ assert_equal [], nil_cleaner_wrapper.framework_trace
+ end
+
+ test '#full_trace returns application and framework traces' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal exception.backtrace, wrapper.full_trace
+ end
+
+ test '#full_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.full_trace
+ assert_equal [], nil_cleaner_wrapper.full_trace
+ end
+
+ test '#traces returns every trace by category enumerated with an index' do
+ exception = TestError.new("lib/file.rb:42:in `index'", "/gems/rack.rb:43:in `index'")
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal({
+ 'Application Trace' => [ id: 0, trace: "lib/file.rb:42:in `index'" ],
+ 'Framework Trace' => [ id: 1, trace: "/gems/rack.rb:43:in `index'" ],
+ 'Full Trace' => [
+ { id: 0, trace: "lib/file.rb:42:in `index'" },
+ { id: 1, trace: "/gems/rack.rb:43:in `index'" }
+ ]
+ }, wrapper.traces)
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index ad6335f132..3017a9c2d6 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -83,7 +83,7 @@ class MimeTypeTest < ActiveSupport::TestCase
test "parse broken acceptlines" do
accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
end
# Accept header send with user HTTP_USER_AGENT: Mozilla/4.0
@@ -91,7 +91,7 @@ class MimeTypeTest < ActiveSupport::TestCase
test "parse other broken acceptlines" do
accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
end
test "custom type" do
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index d5a4d8ee11..6a439be2b5 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -64,7 +64,7 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
end
def test_mounting_works_with_nested_script_name
- get "/foo/sprockets/omg", {}, 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/sprockets/omg'
+ get "/foo/sprockets/omg", headers: { 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/sprockets/omg' }
assert_equal "/foo/sprockets -- /omg", response.body
end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index c609075e6b..d77341bc64 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -39,7 +39,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test "nils are stripped from collections" do
assert_parses(
- {"person" => nil},
+ {"person" => []},
"{\"person\":[null]}", { 'CONTENT_TYPE' => 'application/json' }
)
assert_parses(
@@ -47,7 +47,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
"{\"person\":[\"foo\",null]}", { 'CONTENT_TYPE' => 'application/json' }
)
assert_parses(
- {"person" => nil},
+ {"person" => []},
"{\"person\":[null, null]}", { 'CONTENT_TYPE' => 'application/json' }
)
end
@@ -56,7 +56,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
with_test_routing do
output = StringIO.new
json = "[\"person]\": {\"name\": \"David\"}}"
- post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => ActiveSupport::Logger.new(output)}
+ post "/parse", params: json, headers: { 'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => ActiveSupport::Logger.new(output) }
assert_response :bad_request
output.rewind && err = output.read
assert err =~ /Error occurred while parsing request parameters/
@@ -79,7 +79,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test 'raw_post is not empty for JSON request' do
with_test_routing do
- post '/parse', '{"posts": [{"title": "Post Title"}]}', 'CONTENT_TYPE' => 'application/json'
+ post '/parse', params: '{"posts": [{"title": "Post Title"}]}', headers: { 'CONTENT_TYPE' => 'application/json' }
assert_equal '{"posts": [{"title": "Post Title"}]}', request.raw_post
end
end
@@ -87,7 +87,7 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
private
def assert_parses(expected, actual, headers = {})
with_test_routing do
- post "/parse", actual, headers
+ post "/parse", params: actual, headers: headers
assert_response :ok
assert_equal(expected, TestController.last_request_parameters)
end
@@ -146,7 +146,7 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
private
def assert_parses(expected, actual, headers = {})
with_test_routing(UsersController) do
- post "/parse", actual, headers
+ post "/parse", params: actual, headers: headers
assert_response :ok
assert_equal(expected, UsersController.last_request_parameters)
assert_equal(expected.merge({"action" => "parse"}), UsersController.last_parameters)
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 926472163e..50f69c53cb 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'abstract_unit'
class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
@@ -37,7 +36,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
end
test "parse single utf8 parameter" do
- assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => 'Iñtërnâtiônàlizætiøn_value'},
+ assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => 'Iñtërnâtiônàlizætiøn_value'},
parse_multipart('single_utf8_param'), "request.request_parameters")
assert_equal(
'Iñtërnâtiônàlizætiøn_value',
@@ -45,8 +44,8 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
end
test "parse bracketed utf8 parameter" do
- assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => {
- 'Iñtërnâtiônàlizætiøn_nested_name' => 'Iñtërnâtiônàlizætiøn_value'} },
+ assert_equal({ 'Iñtërnâtiônàlizætiøn_name' => {
+ 'Iñtërnâtiônàlizætiøn_nested_name' => 'Iñtërnâtiônàlizætiøn_value'} },
parse_multipart('bracketed_utf8_param'), "request.request_parameters")
assert_equal(
{'Iñtërnâtiônàlizætiøn_nested_name' => 'Iñtërnâtiônàlizætiøn_value'},
@@ -134,13 +133,13 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
with_test_routing do
fixture = FIXTURE_PATH + "/mona_lisa.jpg"
params = { :uploaded_data => fixture_file_upload(fixture, "image/jpg") }
- post '/read', params
+ post '/read', params: params
end
end
test "uploads and reads file" do
with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
+ post '/read', params: { uploaded_data: fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain") }
assert_equal "File: Hello", response.body
end
end
@@ -152,7 +151,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
get ':action', controller: 'multipart_params_parsing_test/test'
end
headers = { "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x" }
- get "/parse", {}, headers
+ get "/parse", headers: headers
assert_response :ok
end
end
@@ -169,7 +168,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
def parse_multipart(name)
with_test_routing do
headers = fixture(name)
- post "/parse", headers.delete("rack.input"), headers
+ post "/parse", params: headers.delete("rack.input"), headers: headers
assert_response :ok
TestController.last_request_parameters
end
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index 4e99c26e03..bc6716525e 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -95,8 +95,8 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
assert_parses({"action" => nil}, "action")
assert_parses({"action" => {"foo" => nil}}, "action[foo]")
assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar]")
- assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar][]")
- assert_parses({"action" => {"foo" => nil }}, "action[foo][]")
+ assert_parses({"action" => {"foo" => { "bar" => [] }}}, "action[foo][bar][]")
+ assert_parses({"action" => {"foo" => [] }}, "action[foo][]")
assert_parses({"action"=>{"foo"=>[{"bar"=>nil}]}}, "action[foo][][bar]")
end
@@ -147,7 +147,7 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
get ':action', :to => ::QueryStringParsingTest::TestController
end
- get "/parse", nil, "QUERY_STRING" => "foo[]=bar&foo[4]=bar"
+ get "/parse", headers: { "QUERY_STRING" => "foo[]=bar&foo[4]=bar" }
assert_response :bad_request
end
end
@@ -162,8 +162,7 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
middleware.use(EarlyParse)
end
-
- get "/parse", actual
+ get "/parse", params: actual
assert_response :ok
assert_equal(expected, ::QueryStringParsingTest::TestController.last_query_parameters)
end
diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
index 1de05cbf09..365edf849a 100644
--- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -131,7 +131,7 @@ class UrlEncodedParamsParsingTest < ActionDispatch::IntegrationTest
test "ambiguous params returns a bad request" do
with_test_routing do
- post "/parse", "foo[]=bar&foo[4]=bar"
+ post "/parse", params: "foo[]=bar&foo[4]=bar"
assert_response :bad_request
end
end
@@ -148,7 +148,7 @@ class UrlEncodedParamsParsingTest < ActionDispatch::IntegrationTest
def assert_parses(expected, actual)
with_test_routing do
- post "/parse", actual
+ post "/parse", params: actual
assert_response :ok
assert_equal expected, TestController.last_request_parameters
assert_utf8 TestController.last_request_parameters
diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb
index a8050b4fab..a307483509 100644
--- a/actionpack/test/dispatch/request_id_test.rb
+++ b/actionpack/test/dispatch/request_id_test.rb
@@ -41,7 +41,7 @@ class RequestIdResponseTest < ActionDispatch::IntegrationTest
test "request id given on request is passed all the way to the response" do
with_test_route_set do
- get '/', {}, 'HTTP_X_REQUEST_ID' => 'X' * 500
+ get '/', headers: { 'HTTP_X_REQUEST_ID' => 'X' * 500 }
assert_equal "X" * 255, @response.headers["X-Request-Id"]
end
end
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index a58306ea0a..ee8e915610 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -683,6 +683,22 @@ class RequestMethod < BaseRequestTest
end
end
+ test "exception on invalid HTTP method unaffected by I18n settings" do
+ old_locales = I18n.available_locales
+ old_enforce = I18n.config.enforce_available_locales
+
+ begin
+ I18n.available_locales = [:nl]
+ I18n.config.enforce_available_locales = true
+ assert_raise(ActionController::UnknownHttpMethod) do
+ stub_request('REQUEST_METHOD' => '_RANDOM_METHOD').method
+ end
+ ensure
+ I18n.available_locales = old_locales
+ I18n.config.enforce_available_locales = old_enforce
+ end
+ end
+
test "post masquerading as patch" do
request = stub_request(
'REQUEST_METHOD' => 'PATCH',
@@ -981,8 +997,8 @@ class RequestParameterFilter < BaseRequestTest
}
parameter_filter = ActionDispatch::Http::ParameterFilter.new(filter_words)
- before_filter['barg'] = {'bargain'=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}}
- after_filter['barg'] = {'bargain'=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}}
+ before_filter['barg'] = {:bargain=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}}
+ after_filter['barg'] = {:bargain=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}}
assert_equal after_filter, parameter_filter.filter(before_filter)
end
@@ -1127,6 +1143,13 @@ class RequestVariant < BaseRequestTest
end
end
+ test "reset variant" do
+ request = stub_request
+
+ request.variant = nil
+ assert_equal nil, request.variant
+ end
+
test "setting variant with non symbol value" do
request = stub_request
assert_raise ArgumentError do
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 48342e252a..5fbd19acdf 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -231,9 +231,9 @@ class ResponseTest < ActiveSupport::TestCase
assert_equal ['Not Found'], body.each.to_a
end
- test "[response].flatten does not recurse infinitely" do
+ test "[response.to_a].flatten does not recurse infinitely" do
Timeout.timeout(1) do # use a timeout to prevent it stalling indefinitely
- status, headers, body = assert_deprecated { [@response].flatten }
+ status, headers, body = [@response.to_a].flatten
assert_equal @response.status, status
assert_equal @response.headers, headers
assert_equal @response.body, body.each.to_a.join
@@ -251,27 +251,9 @@ class ResponseTest < ActiveSupport::TestCase
status, headers, body = Rack::ContentLength.new(app).call(env)
assert_equal '5', headers['Content-Length']
end
-
- test "implicit destructuring and Array conversion is deprecated" do
- response = ActionDispatch::Response.new(404, { 'Content-Type' => 'text/plain' }, ['Not Found'])
-
- assert_deprecated do
- status, headers, body = response
-
- assert_equal 404, status
- assert_equal({ 'Content-Type' => 'text/plain' }, headers)
- assert_equal ['Not Found'], body.each.to_a
- end
-
- assert_deprecated { response.to_ary }
- end
end
class ResponseIntegrationTest < ActionDispatch::IntegrationTest
- def app
- @app
- end
-
test "response cache control from railsish app" do
@app = lambda { |env|
ActionDispatch::Response.new.tap { |resp|
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index ff33dd5652..3d3d4b74ae 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -2,6 +2,11 @@ require 'abstract_unit'
require 'rails/engine'
require 'action_dispatch/routing/inspector'
+class MountedRackApp
+ def self.call(env)
+ end
+end
+
module ActionDispatch
module Routing
class RoutesInspectorTest < ActiveSupport::TestCase
@@ -204,19 +209,36 @@ module ActionDispatch
], output
end
- class RackApp
- def self.call(env)
+ def test_rake_routes_shows_route_with_rack_app
+ output = draw do
+ get 'foo/:id' => MountedRackApp, :id => /[A-Z]\d{5}/
end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " GET /foo/:id(.:format) MountedRackApp {:id=>/[A-Z]\\d{5}/}"
+ ], output
end
- def test_rake_routes_shows_route_with_rack_app
+ def test_rake_routes_shows_named_route_with_mounted_rack_app
output = draw do
- get 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ mount MountedRackApp => '/foo'
end
assert_equal [
- "Prefix Verb URI Pattern Controller#Action",
- " GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"
+ " Prefix Verb URI Pattern Controller#Action",
+ "mounted_rack_app /foo MountedRackApp"
+ ], output
+ end
+
+ def test_rake_routes_shows_overridden_named_route_with_mounted_rack_app_with_name
+ output = draw do
+ mount MountedRackApp => '/foo', as: 'blog'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " blog /foo MountedRackApp"
], output
end
@@ -229,21 +251,21 @@ module ActionDispatch
output = draw do
scope :constraint => constraint.new do
- mount RackApp => '/foo'
+ mount MountedRackApp => '/foo'
end
end
assert_equal [
- "Prefix Verb URI Pattern Controller#Action",
- " /foo #{RackApp.name} {:constraint=>( my custom constraint )}"
+ " Prefix Verb URI Pattern Controller#Action",
+ "mounted_rack_app /foo MountedRackApp {:constraint=>( my custom constraint )}"
], output
end
def test_rake_routes_dont_show_app_mounted_in_assets_prefix
output = draw do
- get '/sprockets' => RackApp
+ get '/sprockets' => MountedRackApp
end
- assert_no_match(/RackApp/, output.first)
+ assert_no_match(/MountedRackApp/, output.first)
assert_no_match(/\/sprockets/, output.first)
end
diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb
index c465d56bde..fe52c50336 100644
--- a/actionpack/test/dispatch/routing/route_set_test.rb
+++ b/actionpack/test/dispatch/routing/route_set_test.rb
@@ -69,6 +69,42 @@ module ActionDispatch
end
end
+ test "only_path: true with *_url and no :host option" do
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_equal '/foo', url_helpers.foo_url(only_path: true)
+ end
+
+ test "only_path: false with *_url and no :host option" do
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_raises ArgumentError do
+ assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false)
+ end
+ end
+
+ test "only_path: false with *_url and local :host option" do
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false, host: 'example.com')
+ end
+
+ test "only_path: false with *_url and global :host option" do
+ @set.default_url_options = { host: 'example.com' }
+
+ draw do
+ get 'foo', to: SimpleApp.new('foo#index')
+ end
+
+ assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false)
+ end
+
test "explicit keys win over implicit keys" do
draw do
resources :foo do
@@ -80,6 +116,18 @@ module ActionDispatch
assert_equal '/foo/1/bar/2', url_helpers.foo_bar_path(2, foo_id: 1)
end
+ test "having an optional scope with resources" do
+ draw do
+ scope "(/:foo)" do
+ resources :users
+ end
+ end
+
+ assert_equal '/users/1', url_helpers.user_path(1)
+ assert_equal '/users/1', url_helpers.user_path(1, foo: nil)
+ assert_equal '/a/users/1', url_helpers.user_path(1, foo: 'a')
+ end
+
private
def draw(&block)
@set.draw(&block)
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index d141210ad9..ca5de05814 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -362,22 +362,22 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get 'admin/passwords' => "queenbee#passwords", :constraints => ::TestRoutingMapper::IpRestrictor
end
- get '/admin', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ get '/admin', headers: { 'REMOTE_ADDR' => '192.168.1.100' }
assert_equal 'queenbee#index', @response.body
- get '/admin', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ get '/admin', headers: { 'REMOTE_ADDR' => '10.0.0.100' }
assert_equal 'pass', @response.headers['X-Cascade']
- get '/admin/accounts', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ get '/admin/accounts', headers: { 'REMOTE_ADDR' => '192.168.1.100' }
assert_equal 'queenbee#accounts', @response.body
- get '/admin/accounts', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ get '/admin/accounts', headers: { 'REMOTE_ADDR' => '10.0.0.100' }
assert_equal 'pass', @response.headers['X-Cascade']
- get '/admin/passwords', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ get '/admin/passwords', headers: { 'REMOTE_ADDR' => '192.168.1.100' }
assert_equal 'queenbee#passwords', @response.body
- get '/admin/passwords', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ get '/admin/passwords', headers: { 'REMOTE_ADDR' => '10.0.0.100' }
assert_equal 'pass', @response.headers['X-Cascade']
end
@@ -1683,9 +1683,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get '/products/0001/images/0001'
assert_equal 'images#show', @response.body
- get '/dashboard', {}, {'REMOTE_ADDR' => '10.0.0.100'}
+ get '/dashboard', headers: { 'REMOTE_ADDR' => '10.0.0.100' }
assert_equal 'pass', @response.headers['X-Cascade']
- get '/dashboard', {}, {'REMOTE_ADDR' => '192.168.1.100'}
+ get '/dashboard', headers: { 'REMOTE_ADDR' => '192.168.1.100' }
assert_equal 'dashboards#show', @response.body
end
@@ -3331,30 +3331,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal 'comments#index', @response.body
end
- def test_mix_symbol_to_controller_action
- assert_deprecated do
- draw do
- get '/projects', controller: 'project_files',
- action: 'index',
- to: :show
- end
- end
- get '/projects'
- assert_equal 'project_files#show', @response.body
- end
-
- def test_mix_string_to_controller_action_no_hash
- assert_deprecated do
- draw do
- get '/projects', controller: 'project_files',
- action: 'index',
- to: 'show'
- end
- end
- get '/projects'
- assert_equal 'show#index', @response.body
- end
-
def test_shallow_path_and_prefix_are_not_added_to_non_shallow_routes
draw do
scope shallow_path: 'projects', shallow_prefix: 'project' do
@@ -3463,6 +3439,56 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal '/bar/comments/1', comment_path('1')
end
+ def test_resource_where_as_is_empty
+ draw do
+ resource :post, as: ''
+
+ scope 'post', as: 'post' do
+ resource :comment, as: ''
+ end
+ end
+
+ assert_equal '/post/new', new_path
+ assert_equal '/post/comment/new', new_post_path
+ end
+
+ def test_resources_where_as_is_empty
+ draw do
+ resources :posts, as: ''
+
+ scope 'posts', as: 'posts' do
+ resources :comments, as: ''
+ end
+ end
+
+ assert_equal '/posts/new', new_path
+ assert_equal '/posts/comments/new', new_posts_path
+ end
+
+ def test_scope_where_as_is_empty
+ draw do
+ scope 'post', as: '' do
+ resource :user
+ resources :comments
+ end
+ end
+
+ assert_equal '/post/user/new', new_user_path
+ assert_equal '/post/comments/new', new_comment_path
+ end
+
+ def test_head_fetch_with_mount_on_root
+ draw do
+ get '/home' => 'test#index'
+ mount lambda { |env| [404, {"Content-Type" => "text/html"}, ["testing"]] }, at: '/'
+ end
+ head '/home'
+ assert_response :success
+
+ head '/'
+ assert_response :not_found
+ end
+
private
def draw(&block)
@@ -3559,12 +3585,12 @@ class TestAltApp < ActionDispatch::IntegrationTest
end
def test_alt_request_with_matched_header
- get "/", {}, "HTTP_X_HEADER" => "HEADER"
+ get "/", headers: { "HTTP_X_HEADER" => "HEADER" }
assert_equal "XHeader", @response.body
end
def test_alt_request_with_unmatched_header
- get "/", {}, "HTTP_X_HEADER" => "NON_MATCH"
+ get "/", headers: { "HTTP_X_HEADER" => "NON_MATCH" }
assert_equal "Alternative App", @response.body
end
end
@@ -3629,15 +3655,13 @@ class TestNamespaceWithControllerOption < ActionDispatch::IntegrationTest
assert_match(/Missing :controller/, ex.message)
end
- def test_missing_action
+ def test_missing_controller_with_to
ex = assert_raises(ArgumentError) {
- assert_deprecated do
- draw do
- get '/foo/bar', :to => 'foo'
- end
+ draw do
+ get '/foo/bar', :to => 'foo'
end
}
- assert_match(/Missing :action/, ex.message)
+ assert_match(/Missing :controller/, ex.message)
end
def test_missing_action_on_hash
@@ -3761,7 +3785,7 @@ class TestHttpMethods < ActionDispatch::IntegrationTest
(RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC4791 + RFC5789).each do |method|
test "request method #{method.underscore} can be matched" do
- get '/', nil, 'REQUEST_METHOD' => method
+ get '/', headers: { 'REQUEST_METHOD' => method }
assert_equal method, @response.body
end
end
@@ -4420,7 +4444,7 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest
include Routes.url_helpers
- test "url helpers raise a helpful error message whem generation fails" do
+ test "url helpers raise a helpful error message when generation fails" do
url, missing = { action: 'show', controller: 'products', id: nil }, [:id]
message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}"
@@ -4433,3 +4457,31 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest
assert_equal message, error.message
end
end
+
+class TestDefaultUrlOptions < ActionDispatch::IntegrationTest
+ class PostsController < ActionController::Base
+ def archive
+ render :text => "posts#archive"
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ default_url_options locale: 'en'
+ scope ':locale', format: false do
+ get '/posts/:year/:month/:day', to: 'posts#archive', as: 'archived_posts'
+ end
+ end
+
+ APP = build_app Routes
+
+ def app
+ APP
+ end
+
+ include Routes.url_helpers
+
+ def test_positional_args_with_format_false
+ assert_equal '/en/posts/2014/12/13', archived_posts_path(2014, 12, 13)
+ end
+end
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index c5cd24d06e..2194efa503 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -125,7 +125,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
def test_does_set_secure_cookies_over_https
with_test_route_set(:secure => true) do
- get '/set_session_value', nil, 'HTTPS' => 'on'
+ get '/set_session_value', headers: { 'HTTPS' => 'on' }
assert_response :success
assert_equal "_myapp_session=#{response.body}; path=/; secure; HttpOnly",
headers['Set-Cookie']
@@ -331,9 +331,11 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
private
# Overwrite get to send SessionSecret in env hash
- def get(path, parameters = nil, env = {})
- env["action_dispatch.key_generator"] ||= Generator
- super
+ def get(path, *args)
+ args[0] ||= {}
+ args[0][:headers] ||= {}
+ args[0][:headers]["action_dispatch.key_generator"] ||= Generator
+ super(path, *args)
end
def with_test_route_set(options = {})
diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb
index f7a06cfed4..fbd82945cc 100644
--- a/actionpack/test/dispatch/session/mem_cache_store_test.rb
+++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb
@@ -172,7 +172,7 @@ class MemCacheStoreTest < ActionDispatch::IntegrationTest
reset!
- get '/set_session_value', :_session_id => session_id
+ get '/set_session_value', params: { _session_id: session_id }
assert_response :success
assert_not_equal session_id, cookies['_session_id']
end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index 323fbc285e..72eaa916bc 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -27,30 +27,30 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
test "skip exceptions app if not showing exceptions" do
@app = ProductionApp
assert_raise RuntimeError do
- get "/", {}, {'action_dispatch.show_exceptions' => false}
+ get "/", headers: { 'action_dispatch.show_exceptions' => false }
end
end
test "rescue with error page" do
@app = ProductionApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 500
assert_equal "500 error fixture\n", body
- get "/bad_params", {}, {'action_dispatch.show_exceptions' => true}
+ get "/bad_params", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 400
assert_equal "400 error fixture\n", body
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_equal "404 error fixture\n", body
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ get "/method_not_allowed", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 405
assert_equal "", body
- get "/unknown_http_method", {}, {'action_dispatch.show_exceptions' => true}
+ get "/unknown_http_method", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 405
assert_equal "", body
end
@@ -61,11 +61,11 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
begin
@app = ProductionApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 500
assert_equal "500 localized error fixture\n", body
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_equal "404 error fixture\n", body
ensure
@@ -76,14 +76,14 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
test "sets the HTTP charset parameter" do
@app = ProductionApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
end
test "show registered original exception for wrapped exceptions" do
@app = ProductionApp
- get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found_original_exception", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_match(/404 error/, body)
end
@@ -97,7 +97,7 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
end
@app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
- get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ get "/not_found_original_exception", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 404
assert_equal "YOU FAILED BRO", body
end
@@ -108,7 +108,7 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
end
@app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ get "/method_not_allowed", headers: { 'action_dispatch.show_exceptions' => true }
assert_response 405
assert_equal "", body
end
diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb
index c3598c5e8e..7ced41bc2e 100644
--- a/actionpack/test/dispatch/ssl_test.rb
+++ b/actionpack/test/dispatch/ssl_test.rb
@@ -20,7 +20,7 @@ class SSLTest < ActionDispatch::IntegrationTest
end
def test_allows_https_proxy_header_url
- get "http://example.org/", {}, 'HTTP_X_FORWARDED_PROTO' => "https"
+ get "http://example.org/", headers: { 'HTTP_X_FORWARDED_PROTO' => "https" }
assert_response :success
end
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index 6f7373201c..ebc9d71403 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -1,6 +1,4 @@
-# encoding: utf-8
require 'abstract_unit'
-require 'rbconfig'
require 'zlib'
module StaticTests
@@ -200,7 +198,8 @@ class StaticTest < ActiveSupport::TestCase
}
def setup
- @app = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/public", "public, max-age=60")
+ @root = "#{FIXTURE_LOAD_PATH}/public"
+ @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
end
def public_path
@@ -208,11 +207,28 @@ class StaticTest < ActiveSupport::TestCase
end
include StaticTests
+
+ def test_custom_handler_called_when_file_is_outside_root
+ filename = 'shared.html.erb'
+ assert File.exist?(File.join(@root, '..', filename))
+ env = {
+ "REQUEST_METHOD"=>"GET",
+ "REQUEST_PATH"=>"/..%2F#{filename}",
+ "PATH_INFO"=>"/..%2F#{filename}",
+ "REQUEST_URI"=>"/..%2F#{filename}",
+ "HTTP_VERSION"=>"HTTP/1.1",
+ "SERVER_NAME"=>"localhost",
+ "SERVER_PORT"=>"8080",
+ "QUERY_STRING"=>""
+ }
+ assert_equal(DummyApp.call(nil), @app.call(env))
+ end
end
class StaticEncodingTest < StaticTest
def setup
- @app = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/公共", "public, max-age=60")
+ @root = "#{FIXTURE_LOAD_PATH}/公共"
+ @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
end
def public_path
diff --git a/actionpack/test/dispatch/template_assertions_test.rb b/actionpack/test/dispatch/template_assertions_test.rb
index 3c393f937b..7278754b49 100644
--- a/actionpack/test/dispatch/template_assertions_test.rb
+++ b/actionpack/test/dispatch/template_assertions_test.rb
@@ -10,7 +10,7 @@ class AssertTemplateController < ActionController::Base
end
def render_with_layout
- @variable_for_layout = nil
+ @variable_for_layout = 'hello'
render 'test/hello_world', layout: "layouts/standard"
end
@@ -95,4 +95,16 @@ class AssertTemplateControllerTest < ActionDispatch::IntegrationTest
session.assert_template file: nil
end
end
+
+ def test_assigns_do_not_reset_template_assertion
+ get '/assert_template/render_with_layout'
+ assert_equal 'hello', assigns(:variable_for_layout)
+ assert_template layout: 'layouts/standard'
+ end
+
+ def test_cookies_do_not_reset_template_assertion
+ get '/assert_template/render_with_layout'
+ cookies
+ assert_template layout: 'layouts/standard'
+ end
end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index 65ad8677f3..cc35d4594e 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -18,7 +18,7 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
- assert_equal [1, 2], env.delete("rack.version")
+ assert_equal [1, 3], env.delete("rack.version")
assert_equal "", env.delete("rack.input").string
assert_kind_of StringIO, env.delete("rack.errors")
assert_equal true, env.delete("rack.multithread")
diff --git a/actionpack/test/dispatch/url_generation_test.rb b/actionpack/test/dispatch/url_generation_test.rb
index 8f79e7bf9a..ce1e1d0a6a 100644
--- a/actionpack/test/dispatch/url_generation_test.rb
+++ b/actionpack/test/dispatch/url_generation_test.rb
@@ -39,12 +39,12 @@ module TestUrlGeneration
end
test "the request's SCRIPT_NAME takes precedence over the route" do
- get "/foo", {}, 'SCRIPT_NAME' => "/new", 'action_dispatch.routes' => Routes
+ get "/foo", headers: { 'SCRIPT_NAME' => "/new", 'action_dispatch.routes' => Routes }
assert_equal "/new/foo", response.body
end
test "the request's SCRIPT_NAME wraps the mounted app's" do
- get '/new/bar/foo', {}, 'SCRIPT_NAME' => '/new', 'PATH_INFO' => '/bar/foo', 'action_dispatch.routes' => Routes
+ get '/new/bar/foo', headers: { 'SCRIPT_NAME' => '/new', 'PATH_INFO' => '/bar/foo', 'action_dispatch.routes' => Routes }
assert_equal "/new/bar/foo", response.body
end
diff --git a/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb
new file mode 100644
index 0000000000..7d2326e04d
--- /dev/null
+++ b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb
@@ -0,0 +1,5 @@
+module Admin
+ module UsersHelpeR
+ end
+end
+
diff --git a/actionpack/test/fixtures/localized/hello_world.de.html b/actionpack/test/fixtures/localized/hello_world.de.html
index 4727d7a7e0..a8fc612c60 100644
--- a/actionpack/test/fixtures/localized/hello_world.de.html
+++ b/actionpack/test/fixtures/localized/hello_world.de.html
@@ -1 +1 @@
-Gutten Tag \ No newline at end of file
+Guten Tag \ No newline at end of file
diff --git a/actionpack/test/journey/path/pattern_test.rb b/actionpack/test/journey/path/pattern_test.rb
index 9dfdfc23ed..6939b426f6 100644
--- a/actionpack/test/journey/path/pattern_test.rb
+++ b/actionpack/test/journey/path/pattern_test.rb
@@ -16,6 +16,7 @@ module ActionDispatch
'/:controller(.:format)' => %r{\A/(#{x})(?:\.([^/.?]+))?\Z},
'/:controller/*foo' => %r{\A/(#{x})/(.+)\Z},
'/:controller/*foo/bar' => %r{\A/(#{x})/(.+)/bar\Z},
+ '/:foo|*bar' => %r{\A/(?:([^/.?]+)|(.+))\Z},
}.each do |path, expected|
define_method(:"test_to_regexp_#{path}") do
strexp = Router::Strexp.build(
@@ -39,6 +40,7 @@ module ActionDispatch
'/:controller(.:format)' => %r{\A/(#{x})(?:\.([^/.?]+))?},
'/:controller/*foo' => %r{\A/(#{x})/(.+)},
'/:controller/*foo/bar' => %r{\A/(#{x})/(.+)/bar},
+ '/:foo|*bar' => %r{\A/(?:([^/.?]+)|(.+))},
}.each do |path, expected|
define_method(:"test_to_non_anchored_regexp_#{path}") do
strexp = Router::Strexp.build(
diff --git a/actionpack/test/journey/route/definition/scanner_test.rb b/actionpack/test/journey/route/definition/scanner_test.rb
index 624e6df51a..7a510f1e07 100644
--- a/actionpack/test/journey/route/definition/scanner_test.rb
+++ b/actionpack/test/journey/route/definition/scanner_test.rb
@@ -11,12 +11,25 @@ module ActionDispatch
# /page/:id(/:action)(.:format)
def test_tokens
[
- ['/', [[:SLASH, '/']]],
- ['*omg', [[:STAR, '*omg']]],
- ['/page', [[:SLASH, '/'], [:LITERAL, 'page']]],
- ['/~page', [[:SLASH, '/'], [:LITERAL, '~page']]],
- ['/pa-ge', [[:SLASH, '/'], [:LITERAL, 'pa-ge']]],
- ['/:page', [[:SLASH, '/'], [:SYMBOL, ':page']]],
+ ['/', [[:SLASH, '/']]],
+ ['*omg', [[:STAR, '*omg']]],
+ ['/page', [[:SLASH, '/'], [:LITERAL, 'page']]],
+ ['/page!', [[:SLASH, '/'], [:LITERAL, 'page!']]],
+ ['/page$', [[:SLASH, '/'], [:LITERAL, 'page$']]],
+ ['/page&', [[:SLASH, '/'], [:LITERAL, 'page&']]],
+ ["/page'", [[:SLASH, '/'], [:LITERAL, "page'"]]],
+ ['/page*', [[:SLASH, '/'], [:LITERAL, 'page*']]],
+ ['/page+', [[:SLASH, '/'], [:LITERAL, 'page+']]],
+ ['/page,', [[:SLASH, '/'], [:LITERAL, 'page,']]],
+ ['/page;', [[:SLASH, '/'], [:LITERAL, 'page;']]],
+ ['/page=', [[:SLASH, '/'], [:LITERAL, 'page=']]],
+ ['/page@', [[:SLASH, '/'], [:LITERAL, 'page@']]],
+ ['/page\:', [[:SLASH, '/'], [:LITERAL, 'page:']]],
+ ['/page\(', [[:SLASH, '/'], [:LITERAL, 'page(']]],
+ ['/page\)', [[:SLASH, '/'], [:LITERAL, 'page)']]],
+ ['/~page', [[:SLASH, '/'], [:LITERAL, '~page']]],
+ ['/pa-ge', [[:SLASH, '/'], [:LITERAL, 'pa-ge']]],
+ ['/:page', [[:SLASH, '/'], [:SYMBOL, ':page']]],
['/(:page)', [
[:SLASH, '/'],
[:LPAREN, '('],
diff --git a/actionpack/test/journey/router/utils_test.rb b/actionpack/test/journey/router/utils_test.rb
index 9b2b85ec73..2b505f081e 100644
--- a/actionpack/test/journey/router/utils_test.rb
+++ b/actionpack/test/journey/router/utils_test.rb
@@ -1,4 +1,3 @@
-# coding: utf-8
require 'abstract_unit'
module ActionDispatch
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index 8e90d4100f..19c61b5914 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -201,6 +201,16 @@ module ActionDispatch
assert_match(/missing required keys: \[:id\]/, error.message)
end
+ def test_does_not_include_missing_keys_message
+ route_name = "gorby_thunderhorse"
+
+ error = assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(route_name, { }, { })
+ end
+
+ assert_no_match(/missing required keys: \[\]/, error.message)
+ end
+
def test_X_Cascade
add_routes @router, [ "/messages(.:format)" ]
resp = @router.serve(rails_env({ 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/lol' }))
@@ -405,7 +415,7 @@ module ActionDispatch
def test_generate_with_name
path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ @router.routes.add_route @app, path, {}, {}, "tasks"
path, params = @formatter.generate(
"tasks",
diff --git a/actionpack/test/routing/helper_test.rb b/actionpack/test/routing/helper_test.rb
index 09ca7ff73b..0028aaa629 100644
--- a/actionpack/test/routing/helper_test.rb
+++ b/actionpack/test/routing/helper_test.rb
@@ -26,20 +26,6 @@ module ActionDispatch
x.new.pond_duck_path Duck.new
end
end
-
- def test_path_deprecation
- rs = ::ActionDispatch::Routing::RouteSet.new
- rs.draw do
- resources :ducks
- end
-
- x = Class.new {
- include rs.url_helpers(false)
- }
- assert_deprecated do
- assert_equal '/ducks', x.new.ducks_path
- end
- end
end
end
end