views:

1682

answers:

4

In a few of my controllers I have a before_filter that checks if a user is logged in? for CRUD actions.

application.rb

  def logged_in?
    unless current_user
      redirect_to root_path
    end
  end

  private
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end

But now my functional tests fail because its redirecting to root. So I need a way to simulate that a session has been created but nothing I've tried has worked. Heres what I have right now and the tests pretty much ignore it:

test_helper.rb

class ActionController::TestCase
  setup :activate_authlogic
end

posts_controller_test.rb

class PostsControllerTest < ActionController::TestCase
  setup do
    UserSession.create(:username => "dmix", :password => "12345")
  end

  test "should get new" do  
    get :new
    assert_response :success
  end

Am I missing something?

+2  A: 

All I do in my rspec tests for my controller is create a User with Machinist and then assign that user to be the current_user.

def login_user(options = {})
  user = User.make(options)
  @controller.stub!(:current_user).and_return(user)
end

and this attaches the current_user to the controller, which would mean that your logged_in? method would work in your tests.

You obviously would probably need to adapt this to work in Test::Unit, and without Machinist if you don't use it, as I use rspec, but I'm sure the principle is the same.

railsninja
+2  A: 

You should pass ActiveRecord object in UserSession.create

Something like:

u = users(:dmix)
UserSession.create(u)
Anton Mironov
I really encourage you to move away from fixtures for testing if you have an app that doesn't already depend on them. They are tough to maintain, and just frustrating really. Check out the railscast, Factories not Fixtures.
railsninja
+1  A: 

http://authlogic.rubyforge.org/classes/Authlogic/TestCase.html

First you need to activate AuthLogic so that you can use it in your tests.

setup :activate_authlogic

Then you need a valid user record as Anton Mironov pointed out.

Simone Carletti
A: 
edH