Module: RSpec::Rails::ControllerExampleGroup::ClassMethods

Defined in:
lib/rspec/rails/example/controller_example_group.rb

Defined Under Namespace

Classes: DescribedClassDeprecation

Instance Method Summary (collapse)

Instance Method Details

- (Object) controller(base_class = nil, &body)

Note:

Due to Ruby 1.8 scoping rules in anoymous subclasses, constants defined in ApplicationController must be fully qualified (e.g. ApplicationController::AccessDenied) in the block passed to the controller method. Any instance methods, filters, etc, that are defined in ApplicationController, however, are accessible from within the block.

Supports a simple DSL for specifying behavior of ApplicationController. Creates an anonymous subclass of ApplicationController and evals the body in that context. Also sets up implicit routes for this controller, that are separate from those defined in "config/routes.rb".

If you would like to spec a subclass of ApplicationController, call controller like so:

controller(ApplicationControllerSubclass) do
  # ....
end

Examples:


describe ApplicationController do
  controller do
    def index
      raise ApplicationController::AccessDenied
    end
  end
  describe "handling AccessDenied exceptions" do
    it "redirects to the /401.html page" do
      get :index
      response.should redirect_to("/401.html")
    end
  end
end
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rspec/rails/example/controller_example_group.rb', line 57
def controller(base_class = nil, &body)
  root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base
  base_class ||= RSpec.configuration.infer_base_class_for_anonymous_controllers? ?
                   controller_class :
                   root_controller
  base_class ||= root_controller
  new_controller_class = Class.new(base_class) do
    def self.name; "AnonymousController"; end
  end
  new_controller_class.class_eval(&body)
  (class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class }
  [:example_group].delete(:described_class)
  [:example_group].extend DescribedClassDeprecation.new(new_controller_class)
  before do
    @orig_routes = self.routes
    self.routes  = ActionDispatch::Routing::RouteSet.new.tap { |r|
      r.draw { resources :anonymous }
    }
  end
  after do
    self.routes  = @orig_routes
    @orig_routes = nil
  end
end

- (Object) routes(&blk)

Specifies the routeset that will be used for the example group. This is most useful when testing Rails engines.

Examples:


describe MyEngine::PostsController do
  routes { MyEngine::Engine.routes }
  # ...
end
115
116
117
118
119
# File 'lib/rspec/rails/example/controller_example_group.rb', line 115
def routes(&blk)
  before do
    self.routes = blk.call
  end
end