rails plugin testing

I personally think there is not enough written about rails plugin testing, you have to deal with some problems, though, because you don’t have the rails environment on your side. I want to give 2 tips.

Tip 1:

When you extend ActionController::Base within your plugin, put your extensions into a module within a separate file. Then create another file where you extend ActionController::Base like so

require "my_fancy_controller_extension"

class ActionController::Base
  include MyFancyControllerExtension
end

The first advantage of doing it this way is: you can make your extensions protected

class ActionController::Base
  protected

  include MyFancyControllerExtension
end

and you can test your extensions without dealing with permissions: my_fancy_controller_extension_test.rb

class MyFancyControllerExtensionTest < Test::Unit::TestCase
  class DummyController
    include MyFancyControllerExtension
  end

  def test_whatever
    assert DummyController.new....

    # oh yeah, the fancy extensions are not protected within these tests
  end
end

This leads to

Tip 2:

Don’t try to load the whole rails environment within your plugin tests. Loading the whole environment is a lot of work, dependencies, paths, …. Avoid that, where you can. Instead, create dummy controllers, views, models, … to only build the interface neccessary for testing. Use duck typing! One example:

class TestController
  attr_accessor :request, :session, ... # only what your plugin code needs

  class TestRequest
    attr_accessor :host, ...
  end
end

def MyFancyControllerExtensionTest < Test::Unit::TestCase
  def setup
    @controller = TestController.new
  end

  ...
end

This helps a lot when you don’t know where to start your tests.

Leave a Reply

CAPTCHA Image Audio Version
Reload Image