30 June, 2007

ActsAsAuthenticated in test_spec_on_rails

I was having trouble getting "login_as" from the ActsAsAuthenticated plugin to work with test/spec on Rails.

TechnoWeenie suggested doing a def login_as... within each context. (It no longer does; I've put the code from this post into that page now.) That didn't seem very DRY, so I tried including ActsAsAuthenticated all over the place. Nothing worked...

Until I realized the problem: each "context" block creates a new instance of Test::Unit::TestCase. I had assumed it created a new instance of XxxControllerTest. Alas. Easy to fix. Just putTest::Unit::TestCase.send(:include, AuthenticatedTestHelper) before the opening of your XxxControllerTest.

For example:

require File.dirname(__FILE__) + '/../test_helper'
require 'welcome_controller'

Test::Unit::TestCase.send(:include, AuthenticatedTestHelper)

# Re-raise errors caught by the controller.
class WelcomeController; def rescue_action(e) raise e end; end

class WelcomeControllerTest < Test::Unit::TestCase
  fixtures :people
  def setup
    @controller = WelcomeController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  context "A logged-in person" do
    setup do
      use_controller WelcomeController
      login_as :yvette_moore

No comments: