Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

92 | Chapter 3: Rails Plugins


TheClass.new do ... end.newsyntax creates an instance of an anonymous class
with the provided class definition. A more verbose, named, equivalent would be:
class MyTestController
# class definition...
end
@controller = MyTestController.new


  • Sometimes, dependencies are complicated enough so as to require actually load-
    ing a full framework. This is the case with the SSL Requirement plugin, which
    actually loadsActionControllerand sets up a controller for testing purposes.
    First, the code loadsActionController(this either requiresRUBYOPT="rubygems"and
    a suitable gem version ofActionController, or setting theACTIONCONTROLLER_PATH
    environment variable to a copy of theActionController source):
    begin
    require 'action_controller'
    rescue LoadError
    if ENV['ACTIONCONTROLLER_PATH'].nil?
    abort <<MSG
    Please set the ACTIONCONTROLLER_PATH environment variable to the directory
    containing the action_controller.rb file.
    MSG
    else
    $LOAD_PATH.unshift << ENV['ACTIONCONTROLLER_PATH']
    begin
    require 'action_controller'
    rescue LoadError
    abort "ActionController could not be found."
    end
    end
    end
    Then, the test code loadsActionController’stest_process, which affords access
    toActionController::TestRequest and ActionController::TestResponse. After
    that, logging is silenced and routes are reloaded:
    require 'action_controller/testprocess'
    require 'test/unit'
    require "#{File.dirname(
    FILE _)}/../lib/ssl_requirement"


ActionController::Base.logger = nil
ActionController::Routing::Routes.reload rescue nil
Finally come the test controller and test case—these follow much the same for-
mat as Rails functional tests, as we have done all of the setup manually.
class SslRequirementController < ActionController::Base
include SslRequirement

ssl_required :a, :b
ssl_allowed :c

# action definitions...
end
Free download pdf