1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_dispatch/testing/test_request.rb
Kir Shatrov 7e350c6705 Fix memoization bug on ActionDispatch::TestRequest#request_method=
TestRequest have been overrriding request_method setter since 2009,
but the actual implementation in Request (not TestRequest) has been
changed since that. Now it's also using @request_method instance
variable to keep the state.

The override in TestRequest have not been calling `super`, which caused
a bug that after accessing #requst_method the value was memoized and
then we've never been able to change it anymore:

```
req = ActionDispatch::TestRequest.create
puts "was: #{req.request_method}" # memoized here
req.request_method = "POST"
puts "became: #{req.request_method}"
```

output:

```
was: GET
became: GET
```

Since the whole purpose of overriding the setter in TestRequest is to
upcase it, I'm changing it to `super(method.to_s.upcase)`
2016-09-22 11:36:23 -04:00

69 lines
1.7 KiB
Ruby

require "active_support/core_ext/hash/indifferent_access"
require "rack/utils"
module ActionDispatch
class TestRequest < Request
DEFAULT_ENV = Rack::MockRequest.env_for("/",
"HTTP_HOST" => "test.host",
"REMOTE_ADDR" => "0.0.0.0",
"HTTP_USER_AGENT" => "Rails Testing",
)
# Create a new test request with default `env` values
def self.create(env = {})
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
env["rack.request.cookie_hash"] ||= {}.with_indifferent_access
new(default_env.merge(env))
end
def self.default_env
DEFAULT_ENV
end
private_class_method :default_env
def request_method=(method)
super(method.to_s.upcase)
end
def host=(host)
set_header("HTTP_HOST", host)
end
def port=(number)
set_header("SERVER_PORT", number.to_i)
end
def request_uri=(uri)
set_header("REQUEST_URI", uri)
end
def path=(path)
set_header("PATH_INFO", path)
end
def action=(action_name)
path_parameters[:action] = action_name.to_s
end
def if_modified_since=(last_modified)
set_header("HTTP_IF_MODIFIED_SINCE", last_modified)
end
def if_none_match=(etag)
set_header("HTTP_IF_NONE_MATCH", etag)
end
def remote_addr=(addr)
set_header("REMOTE_ADDR", addr)
end
def user_agent=(user_agent)
set_header("HTTP_USER_AGENT", user_agent)
end
def accept=(mime_types)
delete_header("action_dispatch.request.accepts")
set_header("HTTP_ACCEPT", Array(mime_types).collect(&:to_s).join(","))
end
end
end