Testing Plugins | 91
- Unlike in the Rails plugin initializer, when running tests, load paths are not set up
automatically, andDependenciesdoes not load missing constants for you. You
need to manually set up the load paths and require any parts of the plugin that you
will be testing, as in this example from the HTTP Authentication plugin:
$LOADPATH << File.dirname( FILE _) + '/../lib/'
require 'http_authentication'
- Similarly, the plugin’sinit.rbfile is not loaded, so you must set up anything your
tests need, such as including your plugin’s modules in theTestCase class:
class HttpBasicAuthenticationTest < Test::Unit::TestCase
include HttpAuthentication::Basic
# ...
end
- You must usually recreate (mock or stub) any Rails functionality involved in
your test. In the case of the HTT PAuthentication plugin, it would be too much
overhead to load the entireActionControllerframework for the tests. The func-
tionality being tested is very simple, and requires very little ofActionController:
def test_authentication_request
authentication_request(@controller, "Megaglobalapp")
assert_equal 'Basic realm="Megaglobalapp"',
@controller.headers["WWW-Authenticate"]
assert_equal :unauthorized, @controller.renders.first[:status]
end
To support this limited subset ofActionController’s features, the test’ssetup
method creates a stub controller:
def setup
@controller = Class.new do
attr_accessor :headers, :renders
def initialize
@headers, @renders = {}, []
end
def request
Class.new do
def env
{'HTTP_AUTHORIZATION' =>
HttpAuthentication::Basic.encode_credentials("dhh", "secret") }
end
end.new
end
def render(options)
self.renders << options
end
end.new
end