Search code examples
ruby-on-railsrubytestingpluginsactionview

How can I test views in a Rails plugin?


I'm writing a Rails plugin that includes some partials. I'd like to test the partials, but I'm having a hard time setting up a test that will render them. There's no associated controller, so I'm just faking one:

require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'

class MyTest < Test::Unit::TestCase
  def setup
    @renderer = ActionController::Base.new
    @renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views'))
  end

  def test_renders_link
    result = @renderer.render(:partial => '/something')
    assert ...
  end
end

But that :render call always blows up. I've tried using an ActionView::Base instead of an ActionController::Base, but that gets even less far.

Has anyone had any success?


Solution

  • The final answer:

    require 'action_controller'
    require 'active_support'
    require 'action_pack'
    require 'action_view'
    require 'action_controller/test_case'
    
    class StubController < ActionController::Base
      helper MyHelper
      append_view_path '...'
      attr_accessor :thing
      def my_partial
        render :partial => '/my_partial', :locals => { :thing => thing }
      end
      def rescue_action(e) raise e end;
    end
    
    class MyTestCase < ActionController::TestCase
      self.controller_class = StubController
      def setup
        @controller.thing = ...
        get :my_partial
        assert ...
      end
    end