test_case_test.rb 25.5 KB
Newer Older
1 2
require 'abstract_unit'
require 'controller/fake_controllers'
3
require 'active_support/json/decoding'
4
require 'rails/engine'
5

6
class TestCaseTest < ActionController::TestCase
7
  class TestController < ActionController::Base
8 9 10 11
    def no_op
      render :text => 'dummy'
    end

12 13
    def set_flash
      flash["test"] = ">#{flash["test"]}<"
14
      render :text => 'ignore me'
15
    end
16

17 18 19 20 21
    def set_flash_now
      flash.now["test_now"] = ">#{flash["test_now"]}<"
      render :text => 'ignore me'
    end

22 23 24 25 26 27
    def set_session
      session['string'] = 'A wonder'
      session[:symbol] = 'it works'
      render :text => 'Success'
    end

28 29 30 31 32
    def reset_the_session
      reset_session
      render :text => 'ignore me'
    end

33
    def render_raw_post
34
      raise ActiveSupport::TestCase::Assertion, "#raw_post is blank" if request.raw_post.blank?
35 36 37
      render :text => request.raw_post
    end

38 39 40 41
    def render_body
      render :text => request.body.read
    end

42 43
    def test_params
      render :text => params.inspect
44 45
    end

46
    def test_uri
47
      render :text => request.fullpath
48
    end
49

50 51 52 53
    def test_format
      render :text => request.format
    end

54 55 56 57
    def test_query_string
      render :text => request.query_string
    end

A
Andrew White 已提交
58 59 60 61
    def test_protocol
      render :text => request.protocol
    end

62
    def test_headers
63
      render text: request.headers.env.to_json
64 65
    end

66
    def test_html_output
67
      render :text => <<HTML
68 69
<html>
  <body>
70
    <a href="/"><img src="/images/button.png" /></a>
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    <div id="foo">
      <ul>
        <li class="item">hello</li>
        <li class="item">goodbye</li>
      </ul>
    </div>
    <div id="bar">
      <form action="/somewhere">
        Name: <input type="text" name="person[name]" id="person_name" />
      </form>
    </div>
  </body>
</html>
HTML
    end
J
Joshua Peek 已提交
86

87 88 89 90 91 92 93 94 95
    def test_xml_output
      response.content_type = "application/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>
</root>
XML
    end
96

97
    def test_only_one_param
98 99 100 101 102
      render :text => (params[:left] && params[:right]) ? "EEP, Both here!" : "OK"
    end

    def test_remote_addr
      render :text => (request.remote_addr || "not specified")
103
    end
104

105 106 107
    def test_file_upload
      render :text => params[:file].size
    end
108

109 110 111 112
    def test_send_file
      send_file(File.expand_path(__FILE__))
    end

113 114 115 116 117 118 119 120
    def redirect_to_same_controller
      redirect_to :controller => 'test', :action => 'test_uri', :id => 5
    end

    def redirect_to_different_controller
      redirect_to :controller => 'fail', :id => 5
    end

121
    def create
J
Jeremy Kemper 已提交
122
      head :created, :location => 'created resource'
123 124
    end

125 126 127 128 129
    def delete_cookie
      cookies.delete("foo")
      render :nothing => true
    end

130 131
    def test_assigns
      @foo = "foo"
132
      @foo_hash = {:foo => :bar}
133 134 135
      render :nothing => true
    end

136 137 138 139 140 141 142 143
    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

144 145 146 147 148
    private

      def generate_url(opts)
        url_for(opts.merge(:action => "test_uri"))
      end
149 150 151
  end

  def setup
152
    super
153 154 155
    @controller = TestController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
C
Carl Lerche 已提交
156
    @request.env['PATH_INFO'] = nil
157 158
    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
159
        get ':controller(/:action(/:id))'
160 161
      end
    end
162 163
  end

164 165 166 167 168 169 170 171 172 173 174
  class ViewAssignsController < ActionController::Base
    def test_assigns
      @foo = "foo"
      render :nothing => true
    end

    def view_assigns
      { "bar" => "bar" }
    end
  end

175
  class DefaultUrlOptionsCachingController < ActionController::Base
176
    before_action { @dynamic_opt = 'opt' }
177 178 179 180 181 182 183 184 185 186 187 188 189 190

    def test_url_options_reset
      render text: url_for(params)
    end

    def default_url_options
      if defined?(@dynamic_opt)
        super.merge dynamic_opt: @dynamic_opt
      else
        super
      end
    end
  end

191 192 193 194 195 196 197 198 199 200 201 202 203
  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

204 205 206 207 208 209 210
  def test_url_options_reset
    @controller = DefaultUrlOptionsCachingController.new
    get :test_url_options_reset
    assert_nil @request.params['dynamic_opt']
    assert_match(/dynamic_opt=opt/, @response.body)
  end

211
  def test_raw_post_handling
212
    params = Hash[:page, {:name => 'page name'}, 'some key', 123]
213
    post :render_raw_post, params.dup
214

215 216 217 218
    assert_equal params.to_query, @response.body
  end

  def test_body_stream
219
    params = Hash[:page, { :name => 'page name' }, 'some key', 123]
220

221
    post :render_body, params.dup
222 223

    assert_equal params.to_query, @response.body
224
  end
225

226 227
  def test_document_body_and_params_with_post
    post :test_params, :id => 1
228
    assert_equal("{\"id\"=>\"1\", \"controller\"=>\"test_case_test/test\", \"action\"=>\"test_params\"}", @response.body)
229
  end
230

231 232 233 234
  def test_document_body_with_post
    post :render_body, "document body"
    assert_equal "document body", @response.body
  end
235

236 237 238 239
  def test_document_body_with_put
    put :render_body, "document body"
    assert_equal "document body", @response.body
  end
240

241 242 243 244 245
  def test_head
    head :test_params
    assert_equal 200, @response.status
  end

G
Guo Xiang Tan 已提交
246
  def test_head_params_as_string
247 248 249
    assert_raise(NoMethodError) { head :test_params, "document body", :id => 10 }
  end

250 251
  def test_process_without_flash
    process :set_flash
252
    assert_equal '><', flash['test']
253 254
  end

255
  def test_process_with_flash
256
    process :set_flash, "GET", nil, nil, { "test" => "value" }
257
    assert_equal '>value<', flash['test']
258
  end
259

260
  def test_process_with_flash_now
261
    process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" }
262 263 264
    assert_equal '>value_now<', flash['test_now']
  end

265 266 267 268 269 270 271 272 273
  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"
    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_process_with_session_arg
274
    process :no_op, "GET", nil, { 'string' => 'value1', :symbol => 'value2' }
275 276 277 278 279 280
    assert_equal 'value1', session['string']
    assert_equal 'value1', session[:string]
    assert_equal 'value2', session['symbol']
    assert_equal 'value2', session[:symbol]
  end

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  def test_process_merges_session_arg
    session[:foo] = 'bar'
    get :no_op, nil, { :bar => 'baz' }
    assert_equal 'bar', session[:foo]
    assert_equal 'baz', session[:bar]
  end

  def test_merged_session_arg_is_retained_across_requests
    get :no_op, nil, { :foo => 'bar' }
    assert_equal 'bar', session[:foo]
    get :no_op
    assert_equal 'bar', session[:foo]
  end

  def test_process_overwrites_existing_session_arg
    session[:foo] = 'bar'
    get :no_op, nil, { :foo => 'baz' }
    assert_equal 'baz', session[:foo]
  end

301 302 303 304 305 306 307 308 309 310 311 312
  def test_session_is_cleared_from_controller_after_reset_session
    process :set_session
    process :reset_the_session
    assert_equal Hash.new, @controller.session.to_hash
  end

  def test_session_is_cleared_from_request_after_reset_session
    process :set_session
    process :reset_the_session
    assert_equal Hash.new, @request.session.to_hash
  end

313 314 315 316 317 318
  def test_response_and_request_have_nice_accessors
    process :no_op
    assert_equal @response, response
    assert_equal @request, request
  end

319 320
  def test_process_with_request_uri_with_no_params
    process :test_uri
321
    assert_equal "/test_case_test/test/test_uri", @response.body
322 323 324
  end

  def test_process_with_request_uri_with_params
325
    process :test_uri, "GET", :id => 7
326
    assert_equal "/test_case_test/test/test_uri/7", @response.body
327
  end
328

329
  def test_process_with_request_uri_with_params_with_explicit_uri
C
Carl Lerche 已提交
330
    @request.env['PATH_INFO'] = "/explicit/uri"
331
    process :test_uri, "GET", :id => 7
332
    assert_equal "/explicit/uri", @response.body
333 334
  end

335
  def test_process_with_query_string
336
    process :test_query_string, "GET", :q => 'test'
337 338 339 340
    assert_equal "q=test", @response.body
  end

  def test_process_with_query_string_with_explicit_uri
C
Carl Lerche 已提交
341 342
    @request.env['PATH_INFO'] = '/explicit/uri'
    @request.env['QUERY_STRING'] = 'q=test?extra=question'
343 344 345 346
    process :test_query_string
    assert_equal "q=test?extra=question", @response.body
  end

347
  def test_multiple_calls
348
    process :test_only_one_param, "GET", :left => true
349
    assert_equal "OK", @response.body
350
    process :test_only_one_param, "GET", :right => true
351
    assert_equal "OK", @response.body
352
  end
353

354 355 356 357 358 359 360 361 362
  def test_assigns
    process :test_assigns
    # assigns can be accessed using assigns(key)
    # or assigns[key], where key is a string or
    # a symbol
    assert_equal "foo", assigns(:foo)
    assert_equal "foo", assigns("foo")
    assert_equal "foo", assigns[:foo]
    assert_equal "foo", assigns["foo"]
363 364 365 366

    # but the assigned variable should not have its own keys stringified
    expected_hash = { :foo => :bar }
    assert_equal expected_hash, assigns(:foo_hash)
367 368
  end

369 370 371 372 373 374 375 376 377
  def test_view_assigns
    @controller = ViewAssignsController.new
    process :test_assigns
    assert_equal nil, assigns(:foo)
    assert_equal nil, assigns[:foo]
    assert_equal "bar", assigns(:bar)
    assert_equal "bar", assigns[:bar]
  end

378 379 380 381 382 383 384 385 386 387 388 389 390
  def test_should_not_impose_childless_html_tags_in_xml
    process :test_xml_output

    begin
      $stderr = StringIO.new
      assert_select 'area' #This will cause a warning if content is processed as HTML
      $stderr.rewind && err = $stderr.read
    ensure
      $stderr = STDERR
    end

    assert err.empty?
  end
391

392
  def test_assert_generates
393
    assert_generates 'controller/action/5', :controller => 'controller', :action => 'action', :id => '5'
394 395 396 397
    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"}, {}
398
  end
399

400 401 402 403
  def test_assert_routing
    assert_routing 'content', :controller => 'content', :action => 'index'
  end

404 405
  def test_assert_routing_with_method
    with_routing do |set|
406
      set.draw { resources(:content) }
407 408 409 410
      assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' })
    end
  end

411
  def test_assert_routing_in_module
412 413 414
    with_routing do |set|
      set.draw do
        namespace :admin do
415
          get 'user' => 'user#index'
416 417 418 419 420
        end
      end

      assert_routing 'admin/user', :controller => 'admin/user', :action => 'index'
    end
421
  end
422

423 424
  def test_assert_routing_with_glob
    with_routing do |set|
425
      set.draw { get('*path' => "pages#show") }
426 427 428
      assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' })
    end
  end
429

430 431 432 433
  def test_params_passing
    get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'}
    parsed_params = eval(@response.body)
    assert_equal(
434
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
435
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
436 437 438 439 440 441 442 443
      parsed_params
    )
  end

  def test_params_passing_with_fixnums
    get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6}
    parsed_params = eval(@response.body)
    assert_equal(
444
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
445
       'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}},
446 447 448 449
      parsed_params
    )
  end

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  def test_params_passing_with_fixnums_when_not_html_request
    get :test_params, :format => 'json', :count => 999
    parsed_params = eval(@response.body)
    assert_equal(
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
       'format' => 'json', 'count' => 999 },
      parsed_params
    )
  end

  def test_params_passing_path_parameter_is_string_when_not_html_request
    get :test_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

470 471
  def test_params_passing_with_frozen_values
    assert_nothing_raised do
472
      get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze, :deepfreeze => { :frozen => 'icy'.freeze }.freeze
473 474 475
    end
    parsed_params = eval(@response.body)
    assert_equal(
476
      {'controller' => 'test_case_test/test', 'action' => 'test_params',
477
       'frozen' => 'icy', 'frozens' => ['icy'], 'deepfreeze' => { 'frozen' => 'icy' }},
478 479 480 481
      parsed_params
    )
  end

482 483 484 485 486 487
  def test_params_passing_doesnt_modify_in_place
    page = {:name => "Page name", :month => 4, :year => 2004, :day => 6}
    get :test_params, :page => page
    assert_equal 2004, page[:year]
  end

488 489 490 491
  test "set additional HTTP headers" do
    @request.headers['Referer'] = "http://nohost.com/home"
    @request.headers['Content-Type'] = "application/rss+xml"
    get :test_headers
492
    parsed_env = ActiveSupport::JSON.decode(@response.body)
493 494 495 496 497 498 499 500
    assert_equal "http://nohost.com/home", parsed_env["HTTP_REFERER"]
    assert_equal "application/rss+xml", parsed_env["CONTENT_TYPE"]
  end

  test "set additional env variables" do
    @request.headers['HTTP_REFERER'] = "http://example.com/about"
    @request.headers['CONTENT_TYPE'] = "application/json"
    get :test_headers
501
    parsed_env = ActiveSupport::JSON.decode(@response.body)
502 503 504 505
    assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
    assert_equal "application/json", parsed_env["CONTENT_TYPE"]
  end

506
  def test_id_converted_to_string
507
    get :test_params, :id => 20, :foo => Object.new
508
    assert_kind_of String, @request.path_parameters[:id]
509 510 511 512
  end

  def test_array_path_parameter_handled_properly
    with_routing do |set|
513
      set.draw do
514 515
        get 'file/*path', :to => 'test_case_test/test#test_params'
        get ':controller/:action'
516
      end
517

518
      get :test_params, :path => ['hello', 'world']
519 520
      assert_equal ['hello', 'world'], @request.path_parameters[:path]
      assert_equal 'hello/world', @request.path_parameters[:path].to_param
521 522 523
    end
  end

G
Godfrey Chan 已提交
524 525 526 527 528 529 530 531 532 533 534 535
  def test_use_route
    with_routing do |set|
      set.draw do
        get 'via_unnamed_route', to: 'test_case_test/test#test_uri'
        get 'via_named_route', as: :a_named_route, to: 'test_case_test/test#test_uri'
      end

      get :test_uri, use_route: :a_named_route
      assert_equal '/via_named_route', @response.body
    end
  end

536 537 538
  def test_assert_realistic_path_parameters
    get :test_params, :id => 20, :foo => Object.new

539
    # All elements of path_parameters should use Symbol keys
540
    @request.path_parameters.each_key do |key|
541
      assert_kind_of Symbol, key
542 543 544 545
    end
  end

  def test_with_routing_places_routes_back
J
Joshua Peek 已提交
546 547
    assert @routes
    routes_id = @routes.object_id
548

549 550 551 552
    begin
      with_routing { raise 'fail' }
      fail 'Should not be here.'
    rescue RuntimeError
553
    end
554

J
Joshua Peek 已提交
555 556
    assert @routes
    assert_equal routes_id, @routes.object_id
557
  end
558 559 560 561 562 563 564 565 566

  def test_remote_addr
    get :test_remote_addr
    assert_equal "0.0.0.0", @response.body

    @request.remote_addr = "192.0.0.1"
    get :test_remote_addr
    assert_equal "192.0.0.1", @response.body
  end
567

568 569 570
  def test_header_properly_reset_after_remote_http_request
    xhr :get, :test_params
    assert_nil @request.env['HTTP_X_REQUESTED_WITH']
G
Guo Xiang Tan 已提交
571
    assert_nil @request.env['HTTP_ACCEPT']
572 573
  end

J
Joshua Peek 已提交
574
  def test_header_properly_reset_after_get_request
575 576 577 578 579
    get :test_params
    @request.recycle!
    assert_nil @request.instance_variable_get("@request_method")
  end

G
Guo Xiang Tan 已提交
580
  def test_params_reset_between_post_requests
581 582
    post :no_op, :foo => "bar"
    assert_equal "bar", @request.params[:foo]
G
Guo Xiang Tan 已提交
583

584
    post :no_op
585
    assert @request.params[:foo].blank?
586 587
  end

588 589 590 591 592 593 594 595
  def test_filtered_parameters_reset_between_requests
    get :no_op, :foo => "bar"
    assert_equal "bar", @request.filtered_parameters[:foo]

    get :no_op, :foo => "baz"
    assert_equal "baz", @request.filtered_parameters[:foo]
  end

G
Guo Xiang Tan 已提交
596
  def test_path_params_reset_between_request
597
    get :test_params, :id => "foo"
598
    assert_equal "foo", @request.path_parameters[:id]
G
Guo Xiang Tan 已提交
599

600
    get :test_params
601
    assert_nil @request.path_parameters[:id]
602 603
  end

A
Andrew White 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616
  def test_request_protocol_is_reset_after_request
    get :test_protocol
    assert_equal "http://", @response.body

    @request.env["HTTPS"] = "on"
    get :test_protocol
    assert_equal "https://", @response.body

    @request.env.delete("HTTPS")
    get :test_protocol
    assert_equal "http://", @response.body
  end

617 618 619 620 621 622 623 624 625 626 627 628 629 630
  def test_request_format
    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

631
  def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
632
    cookies['foo'] = 'bar'
633 634 635 636 637
    get :no_op
    assert_equal 'bar', cookies['foo']
  end

  def test_should_detect_if_cookie_is_deleted
638
    cookies['foo'] = 'bar'
639 640 641 642
    get :delete_cookie
    assert_nil cookies['foo']
  end

643 644 645 646 647 648 649 650
  %w(controller response request).each do |variable|
    %w(get post put delete head process).each do |method|
      define_method("test_#{variable}_missing_for_#{method}_raises_error") do
        remove_instance_variable "@#{variable}"
        begin
          send(method, :test_remote_addr)
          assert false, "expected RuntimeError, got nothing"
        rescue RuntimeError => error
651
          assert_match(%r{@#{variable} is nil}, error.message)
652 653 654 655 656 657
        rescue => error
          assert false, "expected RuntimeError, got #{error.class}"
        end
      end
    end
  end
658

659
  FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart'
660

661 662
  READ_BINARY = 'rb:binary'
  READ_PLAIN = 'r:binary'
663

664 665 666 667
  def test_test_uploaded_file
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
668
    expected = File.read(path)
669
    expected.force_encoding(Encoding::BINARY)
670

J
Joshua Peek 已提交
671
    file = Rack::Test::UploadedFile.new(path, content_type)
672 673 674
    assert_equal filename, file.original_filename
    assert_equal content_type, file.content_type
    assert_equal file.path, file.local_path
675
    assert_equal expected, file.read
676 677 678 679 680

    new_content_type = "new content_type"
    file.content_type = new_content_type
    assert_equal new_content_type, file.content_type

681
  end
J
Joshua Peek 已提交
682

683
  def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case
684
    TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
685 686 687 688 689

    uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png')
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

690 691 692 693
  def test_test_uploaded_file_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/png'
J
Joshua Peek 已提交
694

J
Joshua Peek 已提交
695
    binary_uploaded_file = Rack::Test::UploadedFile.new(path, content_type, :binary)
696
    assert_equal File.open(path, READ_BINARY).read, binary_uploaded_file.read
J
Joshua Peek 已提交
697

J
Joshua Peek 已提交
698
    plain_uploaded_file = Rack::Test::UploadedFile.new(path, content_type)
699
    assert_equal File.open(path, READ_PLAIN).read, plain_uploaded_file.read
700 701 702 703 704 705
  end

  def test_fixture_file_upload_with_binary
    filename = 'mona_lisa.jpg'
    path = "#{FILES_DIR}/#{filename}"
    content_type = 'image/jpg'
J
Joshua Peek 已提交
706

707
    binary_file_upload = fixture_file_upload(path, content_type, :binary)
708
    assert_equal File.open(path, READ_BINARY).read, binary_file_upload.read
J
Joshua Peek 已提交
709

710
    plain_file_upload = fixture_file_upload(path, content_type)
711
    assert_equal File.open(path, READ_PLAIN).read, plain_file_upload.read
712
  end
713

714 715
  def test_fixture_file_upload
    post :test_file_upload, :file => fixture_file_upload(FILES_DIR + "/mona_lisa.jpg", "image/jpg")
J
Jeremy Kemper 已提交
716
    assert_equal '159528', @response.body
717
  end
718

719 720 721 722 723 724 725 726 727 728 729 730
  def test_fixture_file_upload_relative_to_fixture_path
    TestCaseTest.stubs(:fixture_path).returns(FILES_DIR)
    uploaded_file = fixture_file_upload("mona_lisa.jpg", "image/jpg")
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

  def test_fixture_file_upload_ignores_nil_fixture_path
    TestCaseTest.stubs(:fixture_path).returns(nil)
    uploaded_file = fixture_file_upload("#{FILES_DIR}/mona_lisa.jpg", "image/jpg")
    assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read
  end

731 732 733 734 735 736 737
  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))
    assert_equal '159528', @response.body
  end

738
  def test_test_uploaded_file_exception_when_file_doesnt_exist
J
Joshua Peek 已提交
739
    assert_raise(RuntimeError) { Rack::Test::UploadedFile.new('non_existent_file') }
740
  end
741

742 743 744 745 746 747 748 749 750
  def test_redirect_url_only_cares_about_location_header
    get :create
    assert_response :created

    # Redirect url doesn't care that it wasn't a :redirect response.
    assert_equal 'created resource', @response.redirect_url
    assert_equal @response.redirect_url, redirect_to_url

    # Must be a :redirect response.
751
    assert_raise(ActiveSupport::TestCase::Assertion) do
752 753 754
      assert_redirected_to 'created resource'
    end
  end
755
end
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
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

  class BarControllerTestWithHostApplicationRouteSet < ActionController::TestCase
    tests BarController

    def test_use_route
      with_routing do |set|
        set.draw { mount Engine => '/foo' }

        get :index, use_route: :foo
        assert_equal @response.body, 'bar'
      end
    end
  end
end

808
class InferringClassNameTest < ActionController::TestCase
809 810 811 812 813
  def test_determine_controller_class
    assert_equal ContentController, determine_class("ContentControllerTest")
  end

  def test_determine_controller_class_with_nonsense_name
814
    assert_nil determine_class("HelloGoodBye")
815 816 817
  end

  def test_determine_controller_class_with_sensible_name_where_no_controller_exists
818
    assert_nil determine_class("NoControllerWithThisNameTest")
819 820 821 822 823 824 825 826 827 828
  end

  private
    def determine_class(name)
      ActionController::TestCase.determine_default_controller_class(name)
    end
end

class CrazyNameTest < ActionController::TestCase
  tests ContentController
829

830 831 832 833
  def test_controller_class_can_be_set_manually_not_just_inferred
    assert_equal ContentController, self.class.controller_class
  end
end
834

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
class CrazySymbolNameTest < ActionController::TestCase
  tests :content

  def test_set_controller_class_using_symbol
    assert_equal ContentController, self.class.controller_class
  end
end

class CrazyStringNameTest < ActionController::TestCase
  tests 'content'

  def test_set_controller_class_using_string
    assert_equal ContentController, self.class.controller_class
  end
end

851 852
class NamedRoutesControllerTest < ActionController::TestCase
  tests ContentController
J
Joshua Peek 已提交
853

854 855
  def test_should_be_able_to_use_named_routes_before_a_request_is_done
    with_routing do |set|
856
      set.draw { resources :contents }
857
      assert_equal 'http://test.host/contents/new', new_content_url
858
      assert_equal 'http://test.host/contents/1', content_url(:id => 1)
859 860 861
    end
  end
end
A
Andrew White 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881

class AnonymousControllerTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def index
        render :text => params[:controller]
      end
    end.new

    @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
      r.draw do
        get ':controller(/:action(/:id))'
      end
    end
  end

  def test_controller_name
    get :index
    assert_equal 'anonymous', @response.body
  end
882
end
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913

class RoutingDefaultsTest < ActionController::TestCase
  def setup
    @controller = Class.new(ActionController::Base) do
      def post
        render :text => request.fullpath
      end

      def project
        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' }
      end
    end
  end

  def test_route_option_can_be_passed_via_process
    get :post, :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
    assert_equal '/projects/2', @response.body
  end
end