Using @current_user in tests

I am still trying to run this test setup do

    @comment = comments(:hello)     @comment.commenter = "cleb"     @comment.body = "hello"     @comment.user_id = 1     @cuser = User.find_by_id(session[:user_id])   end test "should create comment" do

    assert_difference('Comment.count') do       post :create, :comment => @comment.attributes, :user_id => 2     end

    assert_redirected_to comment_path(assigns(:comment))   end

I get this error

test_should_create_comment(CommentsControllerTest): NoMethodError: undefined method `login' for nil:NilClass

This is from comments.controller

  def create     @cuser = @current_user     @user = User.find(params[:user_id])     @user.comments.create(:user_id => @user.id, :commenter => @cuser.login, :body => params[:comment][:body])     respond_to do |format|      format.js      format.html {redirect_to user_path}     end   end

How do I give the controller the required @current_user ?

(Derived from @current_user = User.find_by_id(session[:user_id])

What am I doing wrong?

The first thing is that you have not noticed that the error is pointing out a bug in your code (as tests should do). You should be checking in create that there is a user logged in (or not allowing access to the action if no-one is logged in). So first you need to add a test to check that the action cannot be accessed if no-one is logged in. In order to get the test you have shown to pass you need to effectively login a user by setting up the session. I have to go so have not time to describe it but if you google for setting session in rails tests then you should easily find it.

Colin