Search code examples
ruby-on-railsactionviewactioncontroller

testing a that Rails controller chooses a layout without rendering the layout


i'd like to stub out render and i'd like to test that a certain layout is chosen

bonus catch: in the test env, that layout file will not exist

is there a clever way to detect if the controller has selected a layout without rendering, and without triggering an ActionView::MissingTemplate error?

(this is on a Rails 2.3 app, but feel free to chat rails 3)


Solution

  • The easiest way to do this is put your layout selection logic in a helper and test the helper directly. No need to stub anything out or fake the rendering.

    class MyController < ActionController::Base
      layout :choose_layout
    
    private
      def choose_layout
        if some_thing?
          'this_layout'
        else
          'other_layout'
        end
      end
    end
    
    class MyControllerTest < ActionController::TestCase
      test "choose_layout" do
        @controller.stubs(:some_thing? => true)
        assert_equal 'other_layout', @controller.send(:choose_layout)
      end
    end