3 require 'active_support/test_case'
5 module ActionController
6 module Integration
#:nodoc:
7 # An integration Session instance represents a set of requests and responses
8 # performed sequentially by some virtual user. Becase you can instantiate
9 # multiple sessions and run them side-by-side, you can also mimic (to some
10 # limited extent) multiple simultaneous users interacting with your system.
12 # Typically, you will instantiate a new session using
13 # IntegrationTest#open_session, rather than instantiating
14 # Integration::Session directly.
16 include Test
::Unit::Assertions
17 include ActionController
::TestCase::Assertions
18 include ActionController
::TestProcess
20 # Rack application to use
21 attr_accessor
:application
23 # The integer HTTP status code of the last request.
26 # The status message that accompanied the status code of the last request.
27 attr_reader
:status_message
29 # The body of the last request.
32 # The URI of the last request.
35 # The hostname used in the last request.
38 # The remote_addr used in the last request.
39 attr_accessor
:remote_addr
41 # The Accept header to send.
44 # A map of the cookies returned by the last response, and which will be
45 # sent with the next request.
48 # A map of the headers returned by the last response.
51 # A reference to the controller instance used by the last request.
52 attr_reader
:controller
54 # A reference to the request instance used by the last request.
57 # A reference to the response instance used by the last request.
60 # A running counter of the number of requests processed.
61 attr_accessor
:request_count
63 class MultiPartNeededException
< Exception
66 # Create and initialize a new Session instance.
67 def initialize(app
= nil)
68 @application = app
|| ActionController
::Dispatcher.new
72 # Resets the instance. This can be used to reset the state information
73 # in an existing session instance, so it can be used from a clean-slate
78 @status = @path = @headers = nil
79 @result = @status_message = nil
82 @controller = @request = @response = nil
85 self.host
= "www.example.com"
86 self.remote_addr
= "127.0.0.1"
87 self.accept
= "text/xml,application/xml,application/xhtml+xml," +
88 "text/html;q=0.9,text/plain;q=0.8,image/png," +
91 unless defined? @named_routes_configured
92 # install the named routes in this session instance.
93 klass
= class << self; self; end
94 Routing
::Routes.install_helpers(klass
)
96 # the helpers are made protected by default--we make them public for
97 # easier access during testing and troubleshooting.
98 klass
.module_eval
{ public
*Routing
::Routes.named_routes
.helpers
}
99 @named_routes_configured = true
103 # Specify whether or not the session should mimic a secure HTTPS request.
106 # session.https!(false)
107 def https
!(flag
= true)
111 # Return +true+ if the session is mimicking a secure HTTPS request.
120 # Set the host name to use in the next request.
122 # session.host! "www.example.com"
127 # Follow a single redirect response. If the last response was not a
128 # redirect, an exception will be raised. Otherwise, the redirect is
129 # performed on the location header.
131 raise "not a redirect! #{@status} #{@status_message}" unless redirect
?
132 get(interpret_uri(headers
['location']))
136 # Performs a request using the specified method, following any subsequent
137 # redirect. Note that the redirects are followed until the response is
138 # not a redirect--this means you may run into an infinite loop if your
139 # redirect loops back to itself.
140 def request_via_redirect(http_method
, path
, parameters
= nil, headers
= nil)
141 send(http_method
, path
, parameters
, headers
)
142 follow_redirect
! while redirect
?
146 # Performs a GET request, following any subsequent redirect.
147 # See +request_via_redirect+ for more information.
148 def get_via_redirect(path
, parameters
= nil, headers
= nil)
149 request_via_redirect(:get, path
, parameters
, headers
)
152 # Performs a POST request, following any subsequent redirect.
153 # See +request_via_redirect+ for more information.
154 def post_via_redirect(path
, parameters
= nil, headers
= nil)
155 request_via_redirect(:post, path
, parameters
, headers
)
158 # Performs a PUT request, following any subsequent redirect.
159 # See +request_via_redirect+ for more information.
160 def put_via_redirect(path
, parameters
= nil, headers
= nil)
161 request_via_redirect(:put, path
, parameters
, headers
)
164 # Performs a DELETE request, following any subsequent redirect.
165 # See +request_via_redirect+ for more information.
166 def delete_via_redirect(path
, parameters
= nil, headers
= nil)
167 request_via_redirect(:delete, path
, parameters
, headers
)
170 # Returns +true+ if the last response was a redirect.
175 # Performs a GET request with the given parameters.
177 # - +path+: The URI (as a String) on which you want to perform a GET
179 # - +parameters+: The HTTP parameters that you want to pass. This may
181 # a Hash, or a String that is appropriately encoded
182 # (<tt>application/x-www-form-urlencoded</tt> or
183 # <tt>multipart/form-data</tt>).
184 # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
185 # automatically be upcased, with the prefix 'HTTP_' added if needed.
187 # This method returns an Response object, which one can use to
188 # inspect the details of the response. Furthermore, if this method was
189 # called from an ActionController::IntegrationTest object, then that
190 # object's <tt>@response</tt> instance variable will point to the same
193 # You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
194 # +put+, +delete+, and +head+.
195 def get(path
, parameters
= nil, headers
= nil)
196 process
:get, path
, parameters
, headers
199 # Performs a POST request with the given parameters. See get() for more
201 def post(path
, parameters
= nil, headers
= nil)
202 process
:post, path
, parameters
, headers
205 # Performs a PUT request with the given parameters. See get() for more
207 def put(path
, parameters
= nil, headers
= nil)
208 process
:put, path
, parameters
, headers
211 # Performs a DELETE request with the given parameters. See get() for
213 def delete(path
, parameters
= nil, headers
= nil)
214 process
:delete, path
, parameters
, headers
217 # Performs a HEAD request with the given parameters. See get() for more
219 def head(path
, parameters
= nil, headers
= nil)
220 process
:head, path
, parameters
, headers
223 # Performs an XMLHttpRequest request with the given parameters, mirroring
224 # a request from the Prototype library.
226 # The request_method is :get, :post, :put, :delete or :head; the
227 # parameters are +nil+, a hash, or a url-encoded or multipart string;
228 # the headers are a hash. Keys are automatically upcased and prefixed
229 # with 'HTTP_' if not already.
230 def xml_http_request(request_method
, path
, parameters
= nil, headers
= nil)
232 headers
['X-Requested-With'] = 'XMLHttpRequest'
233 headers
['Accept'] ||= [Mime
::JS, Mime
::HTML, Mime
::XML, 'text/xml', Mime
::ALL].join(', ')
234 process(request_method
, path
, parameters
, headers
)
236 alias xhr
:xml_http_request
238 # Returns the URL for the given options, according to the rules specified
239 # in the application's routes.
242 controller
.url_for(options
) :
243 generic_url_rewriter
.rewrite(options
)
247 # Tailors the session based on the given URI, setting the HTTPS value
249 def interpret_uri(path
)
250 location
= URI
.parse(path
)
251 https
! URI
::HTTPS === location
if location
.scheme
252 host
! location
.host
if location
.host
253 location
.query
? "#{location.path}?#{location.query}" : location
.path
256 # Performs the actual request.
257 def process(method
, path
, parameters
= nil, headers
= nil)
258 data = requestify(parameters
)
259 path
= interpret_uri(path
) if path
=~
%r
{://}
260 path
= "/#{path}" unless path
[0] == ?/
265 env["QUERY_STRING"] = data
269 env["QUERY_STRING"] ||= ""
271 data = data.is_a
?(IO
) ? data : StringIO
.new(data || '')
274 "REQUEST_METHOD" => method
.to_s
.upcase
,
275 "SERVER_NAME" => host
,
276 "SERVER_PORT" => (https
? ? "443" : "80"),
277 "HTTPS" => https
? ? "on" : "off",
278 "rack.url_scheme" => https
? ? "https" : "http",
281 "REQUEST_URI" => path
,
284 "REMOTE_ADDR" => remote_addr
,
285 "CONTENT_TYPE" => "application/x-www-form-urlencoded",
286 "CONTENT_LENGTH" => data ? data.length
.to_s
: nil,
287 "HTTP_COOKIE" => encode_cookies
,
288 "HTTP_ACCEPT" => accept
,
290 "rack.version" => [0,1],
291 "rack.input" => data,
292 "rack.errors" => StringIO
.new
,
293 "rack.multithread" => true,
294 "rack.multiprocess" => true,
295 "rack.run_once" => false,
300 (headers
|| {}).each
do |key
, value
|
301 key
= key
.to_s
.upcase
.gsub(/-/, "_")
302 key
= "HTTP_#{key}" unless env.has_key
?(key
) || key
=~
/^HTTP_/
306 [ControllerCapture
, ActionController
::ProcessWithTest].each
do |mod
|
307 unless ActionController
::Base < mod
308 ActionController
::Base.class_eval
{ include mod
}
312 ActionController
::Base.clear_last_instantiation
!
315 # Rack::Lint doesn't accept String headers or bodies in Ruby 1.9
316 unless RUBY_VERSION >= '1.9.0' && Rack
.release
<= '0.9.0'
317 app
= Rack
::Lint.new(app
)
320 status
, headers
, body
= app
.call(env)
325 @status = status
.to_i
326 @status_message = StatusCodes
::STATUS_CODES[@status]
328 @headers = Rack
::Utils::HeaderHash.new(headers
)
330 (@headers['Set-Cookie'] || "").split("\n").each
do |cookie
|
331 name
, value
= cookie
.match(/^([^=]*)=([^;]*);/)[1,2]
332 @cookies[name
] = value
336 if body
.is_a
?(String
)
339 body
.each
{ |part
| @body << part
}
342 if @controller = ActionController
::Base.last_instantiation
343 @request = @controller.request
344 @response = @controller.response
345 @controller.send(:set_test_assigns)
347 # Decorate responses from Rack Middleware and Rails Metal
348 # as an Response for the purposes of integration testing
349 @response = Response
.new
350 @response.status
= status
.to_s
351 @response.headers
.replace(@headers)
352 @response.body
= @body
355 # Decorate the response with the standard behavior of the
356 # TestResponse so that things like assert_response can be
357 # used in integration tests.
358 @response.extend(TestResponseBehavior
)
361 rescue MultiPartNeededException
362 boundary
= "----------XnJLe9ZIbbGUYtzPQJ16u1"
363 status
= process(method
, path
,
364 multipart_body(parameters
, boundary
),
365 (headers
|| {}).merge(
366 {"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"}))
370 # Encode the cookies hash in a format suitable for passing to a
373 cookies
.inject("") do |string
, (name
, value
)|
374 string
<< "#{name}=#{value}; "
378 # Get a temporary URL writer object
379 def generic_url_rewriter
381 'REQUEST_METHOD' => "GET",
382 'QUERY_STRING' => "",
383 "REQUEST_URI" => "/",
385 "SERVER_PORT" => https
? ? "443" : "80",
386 "HTTPS" => https
? ? "on" : "off"
388 UrlRewriter
.new(Request
.new(env), {})
391 def name_with_prefix(prefix
, name
)
392 prefix
? "#{prefix}[#{name}]" : name
.to_s
395 # Convert the given parameters to a request string. The parameters may
396 # be a string, +nil+, or a Hash.
397 def requestify(parameters
, prefix
=nil)
398 if TestUploadedFile
=== parameters
399 raise MultiPartNeededException
400 elsif Hash
=== parameters
401 return nil if parameters
.empty
?
402 parameters
.map
{ |k
,v
|
403 requestify(v
, name_with_prefix(prefix
, k
))
405 elsif Array
=== parameters
407 requestify(v
, name_with_prefix(prefix
, ""))
412 "#{CGI.escape(prefix)}=#{CGI.escape(parameters.to_s)}"
416 def multipart_requestify(params
, first
=true)
417 returning Hash
.new
do |p
|
418 params
.each
do |key
, value
|
419 k
= first
? CGI
.escape(key
.to_s
) : "[#{CGI.escape(key.to_s)}]"
421 multipart_requestify(value
, false).each
do |subkey
, subvalue
|
422 p
[k
+ subkey
] = subvalue
431 def multipart_body(params
, boundary
)
432 multipart_requestify(params
).map
do |key
, value
|
433 if value
.respond_to
?(:original_filename)
434 File
.open(value
.path
, "rb") do |f
|
435 f
.set_encoding(Encoding
::BINARY) if f
.respond_to
?(:set_encoding)
439 Content-Disposition: form-data; name="#{key}"; filename="#{CGI.escape(value.original_filename)}"\r
440 Content-Type: #{value.content_type}\r
441 Content-Length: #{File.stat(value.path).size}\r
449 Content-Disposition: form-data; name="#{key}"\r
454 end.join("")+"--#{boundary}--\r"
458 # A module used to extend ActionController::Base, so that integration tests
459 # can capture the controller used to satisfy a request.
460 module ControllerCapture
#:nodoc:
461 def self.included(base
)
462 base
.extend(ClassMethods
)
465 alias_method_chain
:new, :capture
470 module ClassMethods
#:nodoc:
471 mattr_accessor
:last_instantiation
473 def clear_last_instantiation
!
474 self.last_instantiation
= nil
477 def new_with_capture(*args
)
478 controller
= new_without_capture(*args
)
479 self.last_instantiation
||= controller
486 # Reset the current session. This is useful for testing multiple sessions
487 # in a single test case.
489 @integration_session = open_session
492 %w(get post put head delete cookies assigns
493 xml_http_request xhr get_via_redirect post_via_redirect
).each
do |method
|
494 define_method(method
) do |*args
|
495 reset
! unless @integration_session
496 # reset the html_document variable, but only for new get/post calls
497 @html_document = nil unless %w(cookies assigns
).include?(method
)
498 returning
@integration_session.__send__(method
, *args
) do
499 copy_session_variables
!
504 # Open a new session instance. If a block is given, the new session is
505 # yielded to the block before being returned.
507 # session = open_session do |sess|
508 # sess.extend(CustomAssertions)
511 # By default, a single session is automatically created for you, but you
512 # can use this method to open multiple sessions that ought to be tested
514 def open_session(application
= nil)
515 session
= Integration
::Session.new(application
)
517 # delegate the fixture accessors back to the test instance
518 extras
= Module
.new
{ attr_accessor
:delegate, :test_result }
519 if self.class.respond_to
?(:fixture_table_names)
520 self.class.fixture_table_names
.each
do |table_name
|
521 name
= table_name
.tr(".", "_")
522 next unless respond_to
?(name
)
523 extras
.__send__(:define_method, name
) { |*args
|
524 delegate
.send(name
, *args
)
529 # delegate add_assertion to the test case
530 extras
.__send__(:define_method, :add_assertion) {
531 test_result
.add_assertion
533 session
.extend(extras
)
534 session
.delegate
= self
535 session
.test_result
= @_result
537 yield session
if block_given
?
541 # Copy the instance variables from the current session instance into the
543 def copy_session_variables
! #:nodoc:
544 return unless @integration_session
545 %w(controller response request
).each
do |var
|
546 instance_variable_set("@#{var}", @integration_session.__send__(var
))
550 # Delegate unhandled messages to the current session instance.
551 def method_missing(sym
, *args
, &block
)
552 reset
! unless @integration_session
553 returning
@integration_session.__send__(sym
, *args
, &block
) do
554 copy_session_variables
!
560 # An IntegrationTest is one that spans multiple controllers and actions,
561 # tying them all together to ensure they work together as expected. It tests
562 # more completely than either unit or functional tests do, exercising the
563 # entire stack, from the dispatcher to the database.
565 # At its simplest, you simply extend IntegrationTest and write your tests
566 # using the get/post methods:
568 # require "#{File.dirname(__FILE__)}/test_helper"
570 # class ExampleTest < ActionController::IntegrationTest
574 # # get the login page
576 # assert_equal 200, status
578 # # post the login and follow through to the home page
579 # post "/login", :username => people(:jamis).username,
580 # :password => people(:jamis).password
582 # assert_equal 200, status
583 # assert_equal "/home", path
587 # However, you can also have multiple session instances open per test, and
588 # even extend those instances with assertions and methods to create a very
589 # powerful testing DSL that is specific for your application. You can even
590 # reference any named routes you happen to have defined!
592 # require "#{File.dirname(__FILE__)}/test_helper"
594 # class AdvancedTest < ActionController::IntegrationTest
595 # fixtures :people, :rooms
597 # def test_login_and_speak
598 # jamis, david = login(:jamis), login(:david)
599 # room = rooms(:office)
602 # jamis.speak(room, "anybody home?")
605 # david.speak(room, "hello!")
610 # module CustomAssertions
612 # # reference a named route, for maximum internal consistency!
613 # get(room_url(:id => room.id))
618 # def speak(room, message)
619 # xml_http_request "/say/#{room.id}", :message => message
626 # open_session do |sess|
627 # sess.extend(CustomAssertions)
629 # sess.post "/login", :username => who.username,
630 # :password => who.password
635 class IntegrationTest
< ActiveSupport
::TestCase
636 include Integration
::Runner
638 # Work around a bug in test/unit caused by the default test being named
639 # as a symbol (:default_test), which causes regex test filters
640 # (like "ruby test.rb -n /foo/") to fail because =~ doesn't work on
642 def initialize(name
) #:nodoc:
646 # Work around test/unit's requirement that every subclass of TestCase have
647 # at least one test method. Note that this implementation extends to all
648 # subclasses, as well, so subclasses of IntegrationTest may also exist
649 # without any test methods.
650 def run(*args
) #:nodoc:
651 return if @method_name == "default_test"
655 # Because of how use_instantiated_fixtures and use_transactional_fixtures
656 # are defined, we need to treat them as special cases. Otherwise, users
657 # would potentially have to set their values for both Test::Unit::TestCase
658 # ActionController::IntegrationTest, since by the time the value is set on
659 # TestCase, IntegrationTest has already been defined and cannot inherit
660 # changes to those variables. So, we make those two attributes
664 def use_transactional_fixtures
=(flag
) #:nodoc:
665 @_use_transactional_fixtures = true
666 @use_transactional_fixtures = flag
669 def use_instantiated_fixtures
=(flag
) #:nodoc:
670 @_use_instantiated_fixtures = true
671 @use_instantiated_fixtures = flag
674 def use_transactional_fixtures
#:nodoc:
675 @_use_transactional_fixtures ?
676 @use_transactional_fixtures :
677 superclass
.use_transactional_fixtures
680 def use_instantiated_fixtures
#:nodoc:
681 @_use_instantiated_fixtures ?
682 @use_instantiated_fixtures :
683 superclass
.use_instantiated_fixtures