3
require 'active_support/test_case'
4
require 'action_controller/rack_lint_patch'
6
module ActionController
7
module Integration #:nodoc:
8
# An integration Session instance represents a set of requests and responses
9
# performed sequentially by some virtual user. Because you can instantiate
10
# multiple sessions and run them side-by-side, you can also mimic (to some
11
# limited extent) multiple simultaneous users interacting with your system.
13
# Typically, you will instantiate a new session using
14
# IntegrationTest#open_session, rather than instantiating
15
# Integration::Session directly.
17
include Test::Unit::Assertions
18
include ActionController::TestCase::Assertions
19
include ActionController::TestProcess
21
# Rack application to use
22
attr_accessor :application
24
# The integer HTTP status code of the last request.
27
# The status message that accompanied the status code of the last request.
28
attr_reader :status_message
30
# The body of the last request.
33
# The URI of the last request.
36
# The hostname used in the last request.
39
# The remote_addr used in the last request.
40
attr_accessor :remote_addr
42
# The Accept header to send.
45
# A map of the cookies returned by the last response, and which will be
46
# sent with the next request.
49
# A map of the headers returned by the last response.
52
# A reference to the controller instance used by the last request.
53
attr_reader :controller
55
# A reference to the request instance used by the last request.
58
# A reference to the response instance used by the last request.
61
# A running counter of the number of requests processed.
62
attr_accessor :request_count
64
class MultiPartNeededException < Exception
67
# Create and initialize a new Session instance.
68
def initialize(app = nil)
69
@application = app || ActionController::Dispatcher.new
73
# Resets the instance. This can be used to reset the state information
74
# in an existing session instance, so it can be used from a clean-slate
79
@status = @path = @headers = nil
80
@result = @status_message = nil
83
@controller = @request = @response = nil
86
self.host = "www.example.com"
87
self.remote_addr = "127.0.0.1"
88
self.accept = "text/xml,application/xml,application/xhtml+xml," +
89
"text/html;q=0.9,text/plain;q=0.8,image/png," +
92
unless defined? @named_routes_configured
93
# install the named routes in this session instance.
94
klass = class << self; self; end
95
Routing::Routes.install_helpers(klass)
97
# the helpers are made protected by default--we make them public for
98
# easier access during testing and troubleshooting.
99
klass.module_eval { public *Routing::Routes.named_routes.helpers }
100
@named_routes_configured = true
104
# Specify whether or not the session should mimic a secure HTTPS request.
107
# session.https!(false)
108
def https!(flag = true)
112
# Return +true+ if the session is mimicking a secure HTTPS request.
121
# Set the host name to use in the next request.
123
# session.host! "www.example.com"
128
# Follow a single redirect response. If the last response was not a
129
# redirect, an exception will be raised. Otherwise, the redirect is
130
# performed on the location header.
132
raise "not a redirect! #{@status} #{@status_message}" unless redirect?
133
get(interpret_uri(headers['location']))
137
# Performs a request using the specified method, following any subsequent
138
# redirect. Note that the redirects are followed until the response is
139
# not a redirect--this means you may run into an infinite loop if your
140
# redirect loops back to itself.
141
def request_via_redirect(http_method, path, parameters = nil, headers = nil)
142
send(http_method, path, parameters, headers)
143
follow_redirect! while redirect?
147
# Performs a GET request, following any subsequent redirect.
148
# See +request_via_redirect+ for more information.
149
def get_via_redirect(path, parameters = nil, headers = nil)
150
request_via_redirect(:get, path, parameters, headers)
153
# Performs a POST request, following any subsequent redirect.
154
# See +request_via_redirect+ for more information.
155
def post_via_redirect(path, parameters = nil, headers = nil)
156
request_via_redirect(:post, path, parameters, headers)
159
# Performs a PUT request, following any subsequent redirect.
160
# See +request_via_redirect+ for more information.
161
def put_via_redirect(path, parameters = nil, headers = nil)
162
request_via_redirect(:put, path, parameters, headers)
165
# Performs a DELETE request, following any subsequent redirect.
166
# See +request_via_redirect+ for more information.
167
def delete_via_redirect(path, parameters = nil, headers = nil)
168
request_via_redirect(:delete, path, parameters, headers)
171
# Returns +true+ if the last response was a redirect.
176
# Performs a GET request with the given parameters.
178
# - +path+: The URI (as a String) on which you want to perform a GET
180
# - +parameters+: The HTTP parameters that you want to pass. This may
182
# a Hash, or a String that is appropriately encoded
183
# (<tt>application/x-www-form-urlencoded</tt> or
184
# <tt>multipart/form-data</tt>).
185
# - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
186
# automatically be upcased, with the prefix 'HTTP_' added if needed.
188
# This method returns an Response object, which one can use to
189
# inspect the details of the response. Furthermore, if this method was
190
# called from an ActionController::IntegrationTest object, then that
191
# object's <tt>@response</tt> instance variable will point to the same
194
# You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
195
# +put+, +delete+, and +head+.
196
def get(path, parameters = nil, headers = nil)
197
process :get, path, parameters, headers
200
# Performs a POST request with the given parameters. See get() for more
202
def post(path, parameters = nil, headers = nil)
203
process :post, path, parameters, headers
206
# Performs a PUT request with the given parameters. See get() for more
208
def put(path, parameters = nil, headers = nil)
209
process :put, path, parameters, headers
212
# Performs a DELETE request with the given parameters. See get() for
214
def delete(path, parameters = nil, headers = nil)
215
process :delete, path, parameters, headers
218
# Performs a HEAD request with the given parameters. See get() for more
220
def head(path, parameters = nil, headers = nil)
221
process :head, path, parameters, headers
224
# Performs an XMLHttpRequest request with the given parameters, mirroring
225
# a request from the Prototype library.
227
# The request_method is :get, :post, :put, :delete or :head; the
228
# parameters are +nil+, a hash, or a url-encoded or multipart string;
229
# the headers are a hash. Keys are automatically upcased and prefixed
230
# with 'HTTP_' if not already.
231
def xml_http_request(request_method, path, parameters = nil, headers = nil)
233
headers['X-Requested-With'] = 'XMLHttpRequest'
234
headers['Accept'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
235
process(request_method, path, parameters, headers)
237
alias xhr :xml_http_request
239
# Returns the URL for the given options, according to the rules specified
240
# in the application's routes.
243
controller.url_for(options) :
244
generic_url_rewriter.rewrite(options)
248
# Tailors the session based on the given URI, setting the HTTPS value
250
def interpret_uri(path)
251
location = URI.parse(path)
252
https! URI::HTTPS === location if location.scheme
253
host! location.host if location.host
254
location.query ? "#{location.path}?#{location.query}" : location.path
257
# Performs the actual request.
258
def process(method, path, parameters = nil, headers = nil)
259
data = requestify(parameters)
260
path = interpret_uri(path) if path =~ %r{://}
261
path = "/#{path}" unless path[0] == ?/
266
env["QUERY_STRING"] = data
270
env["QUERY_STRING"] ||= ""
273
data.force_encoding(Encoding::ASCII_8BIT) if data.respond_to?(:force_encoding)
274
data = data.is_a?(IO) ? data : StringIO.new(data)
277
"REQUEST_METHOD" => method.to_s.upcase,
278
"SERVER_NAME" => host,
279
"SERVER_PORT" => (https? ? "443" : "80"),
280
"HTTPS" => https? ? "on" : "off",
281
"rack.url_scheme" => https? ? "https" : "http",
284
"REQUEST_URI" => path,
287
"REMOTE_ADDR" => remote_addr,
288
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
289
"CONTENT_LENGTH" => data ? data.length.to_s : nil,
290
"HTTP_COOKIE" => encode_cookies,
291
"HTTP_ACCEPT" => accept,
293
"rack.version" => [0,1],
294
"rack.input" => data,
295
"rack.errors" => StringIO.new,
296
"rack.multithread" => true,
297
"rack.multiprocess" => true,
298
"rack.run_once" => false
301
(headers || {}).each do |key, value|
302
key = key.to_s.upcase.gsub(/-/, "_")
303
key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
307
[ControllerCapture, ActionController::ProcessWithTest].each do |mod|
308
unless ActionController::Base < mod
309
ActionController::Base.class_eval { include mod }
313
ActionController::Base.clear_last_instantiation!
315
app = Rack::Lint.new(@application)
316
status, headers, body = app.call(env)
321
@status = status.to_i
322
@status_message = StatusCodes::STATUS_CODES[@status]
324
@headers = Rack::Utils::HeaderHash.new(headers)
326
(@headers['Set-Cookie'] || "").split("\n").each do |cookie|
327
name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
328
@cookies[name] = value
332
if body.respond_to?(:to_str)
335
body.each { |part| @body << part }
338
if @controller = ActionController::Base.last_instantiation
339
@request = @controller.request
340
@response = @controller.response
341
@controller.send(:set_test_assigns)
343
# Decorate responses from Rack Middleware and Rails Metal
344
# as an Response for the purposes of integration testing
345
@response = Response.new
346
@response.status = status.to_s
347
@response.headers.replace(@headers)
348
@response.body = @body
351
# Decorate the response with the standard behavior of the
352
# TestResponse so that things like assert_response can be
353
# used in integration tests.
354
@response.extend(TestResponseBehavior)
357
rescue MultiPartNeededException
358
boundary = "----------XnJLe9ZIbbGUYtzPQJ16u1"
359
status = process(method, path,
360
multipart_body(parameters, boundary),
361
(headers || {}).merge(
362
{"CONTENT_TYPE" => "multipart/form-data; boundary=#{boundary}"}))
366
# Encode the cookies hash in a format suitable for passing to a
369
cookies.inject("") do |string, (name, value)|
370
string << "#{name}=#{value}; "
374
# Get a temporary URL writer object
375
def generic_url_rewriter
377
'REQUEST_METHOD' => "GET",
378
'QUERY_STRING' => "",
379
"REQUEST_URI" => "/",
381
"SERVER_PORT" => https? ? "443" : "80",
382
"HTTPS" => https? ? "on" : "off"
384
UrlRewriter.new(Request.new(env), {})
387
def name_with_prefix(prefix, name)
388
prefix ? "#{prefix}[#{name}]" : name.to_s
391
# Convert the given parameters to a request string. The parameters may
392
# be a string, +nil+, or a Hash.
393
def requestify(parameters, prefix=nil)
394
if TestUploadedFile === parameters
395
raise MultiPartNeededException
396
elsif Hash === parameters
397
return nil if parameters.empty?
398
parameters.map { |k,v|
399
requestify(v, name_with_prefix(prefix, k))
401
elsif Array === parameters
403
requestify(v, name_with_prefix(prefix, ""))
408
"#{CGI.escape(prefix)}=#{CGI.escape(parameters.to_s)}"
412
def multipart_requestify(params, first=true)
413
returning Hash.new do |p|
414
params.each do |key, value|
415
k = first ? key.to_s : "[#{key.to_s}]"
417
multipart_requestify(value, false).each do |subkey, subvalue|
418
p[k + subkey] = subvalue
427
def multipart_body(params, boundary)
428
multipart_requestify(params).map do |key, value|
429
if value.respond_to?(:original_filename)
430
File.open(value.path, "rb") do |f|
431
f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding)
435
Content-Disposition: form-data; name="#{key}"; filename="#{CGI.escape(value.original_filename)}"\r
436
Content-Type: #{value.content_type}\r
437
Content-Length: #{File.stat(value.path).size}\r
445
Content-Disposition: form-data; name="#{key}"\r
450
end.join("")+"--#{boundary}--\r"
454
# A module used to extend ActionController::Base, so that integration tests
455
# can capture the controller used to satisfy a request.
456
module ControllerCapture #:nodoc:
457
def self.included(base)
458
base.extend(ClassMethods)
461
alias_method_chain :new, :capture
466
module ClassMethods #:nodoc:
467
mattr_accessor :last_instantiation
469
def clear_last_instantiation!
470
self.last_instantiation = nil
473
def new_with_capture(*args)
474
controller = new_without_capture(*args)
475
self.last_instantiation ||= controller
482
def initialize(*args)
484
@integration_session = nil
487
# Reset the current session. This is useful for testing multiple sessions
488
# in a single test case.
490
@integration_session = open_session
493
%w(get post put head delete cookies assigns
494
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
495
define_method(method) do |*args|
496
reset! unless @integration_session
497
# reset the html_document variable, but only for new get/post calls
498
@html_document = nil unless %w(cookies assigns).include?(method)
499
returning @integration_session.__send__(method, *args) do
500
copy_session_variables!
505
# Open a new session instance. If a block is given, the new session is
506
# yielded to the block before being returned.
508
# session = open_session do |sess|
509
# sess.extend(CustomAssertions)
512
# By default, a single session is automatically created for you, but you
513
# can use this method to open multiple sessions that ought to be tested
515
def open_session(application = nil)
516
session = Integration::Session.new(application)
518
# delegate the fixture accessors back to the test instance
519
extras = Module.new { attr_accessor :delegate, :test_result }
520
if self.class.respond_to?(:fixture_table_names)
521
self.class.fixture_table_names.each do |table_name|
522
name = table_name.tr(".", "_")
523
next unless respond_to?(name)
524
extras.__send__(:define_method, name) { |*args|
525
delegate.send(name, *args)
530
# delegate add_assertion to the test case
531
extras.__send__(:define_method, :add_assertion) {
532
test_result.add_assertion
534
session.extend(extras)
535
session.delegate = self
536
session.test_result = @_result
538
yield session if block_given?
542
# Copy the instance variables from the current session instance into the
544
def copy_session_variables! #:nodoc:
545
return unless @integration_session
546
%w(controller response request).each do |var|
547
instance_variable_set("@#{var}", @integration_session.__send__(var))
551
# Delegate unhandled messages to the current session instance.
552
def method_missing(sym, *args, &block)
553
reset! unless @integration_session
554
if @integration_session.respond_to?(sym)
555
returning @integration_session.__send__(sym, *args, &block) do
556
copy_session_variables!
565
# An IntegrationTest is one that spans multiple controllers and actions,
566
# tying them all together to ensure they work together as expected. It tests
567
# more completely than either unit or functional tests do, exercising the
568
# entire stack, from the dispatcher to the database.
570
# At its simplest, you simply extend IntegrationTest and write your tests
571
# using the get/post methods:
573
# require "#{File.dirname(__FILE__)}/test_helper"
575
# class ExampleTest < ActionController::IntegrationTest
579
# # get the login page
581
# assert_equal 200, status
583
# # post the login and follow through to the home page
584
# post "/login", :username => people(:jamis).username,
585
# :password => people(:jamis).password
587
# assert_equal 200, status
588
# assert_equal "/home", path
592
# However, you can also have multiple session instances open per test, and
593
# even extend those instances with assertions and methods to create a very
594
# powerful testing DSL that is specific for your application. You can even
595
# reference any named routes you happen to have defined!
597
# require "#{File.dirname(__FILE__)}/test_helper"
599
# class AdvancedTest < ActionController::IntegrationTest
600
# fixtures :people, :rooms
602
# def test_login_and_speak
603
# jamis, david = login(:jamis), login(:david)
604
# room = rooms(:office)
607
# jamis.speak(room, "anybody home?")
610
# david.speak(room, "hello!")
615
# module CustomAssertions
617
# # reference a named route, for maximum internal consistency!
618
# get(room_url(:id => room.id))
623
# def speak(room, message)
624
# xml_http_request "/say/#{room.id}", :message => message
631
# open_session do |sess|
632
# sess.extend(CustomAssertions)
634
# sess.post "/login", :username => who.username,
635
# :password => who.password
640
class IntegrationTest < ActiveSupport::TestCase
641
include Integration::Runner
643
# Work around a bug in test/unit caused by the default test being named
644
# as a symbol (:default_test), which causes regex test filters
645
# (like "ruby test.rb -n /foo/") to fail because =~ doesn't work on
647
def initialize(name) #:nodoc:
651
# Work around test/unit's requirement that every subclass of TestCase have
652
# at least one test method. Note that this implementation extends to all
653
# subclasses, as well, so subclasses of IntegrationTest may also exist
654
# without any test methods.
655
def run(*args) #:nodoc:
656
return if @method_name == "default_test"
660
# Because of how use_instantiated_fixtures and use_transactional_fixtures
661
# are defined, we need to treat them as special cases. Otherwise, users
662
# would potentially have to set their values for both Test::Unit::TestCase
663
# ActionController::IntegrationTest, since by the time the value is set on
664
# TestCase, IntegrationTest has already been defined and cannot inherit
665
# changes to those variables. So, we make those two attributes
669
def use_transactional_fixtures=(flag) #:nodoc:
670
@_use_transactional_fixtures = true
671
@use_transactional_fixtures = flag
674
def use_instantiated_fixtures=(flag) #:nodoc:
675
@_use_instantiated_fixtures = true
676
@use_instantiated_fixtures = flag
679
def use_transactional_fixtures #:nodoc:
680
@_use_transactional_fixtures ?
681
@use_transactional_fixtures :
682
superclass.use_transactional_fixtures
685
def use_instantiated_fixtures #:nodoc:
686
@_use_instantiated_fixtures ?
687
@use_instantiated_fixtures :
688
superclass.use_instantiated_fixtures