Ruby on Rails Wednesday, March 28, 2012

On 28 March 2012 20:22, Neil Bye <lists@ruby-forum.com> wrote:
> 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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment