On 28 March 2012 20:22, Neil Bye
<lists-fsXkhYbjdPsEEoCn2XhGlw@public.gmane.org>
wrote:> I am still trying to run this test
> setup do
>
> @comment = comments(:hello)
> -I4CJOCdi0N6MpLzNofplXlAUjnlXr6A1@public.gmane.org = "cleb"
> -I4CJOCdi0N4nHFPqiawQgA@public.gmane.org = "hello"
> -I4CJOCdi0N4BB6bauf/WkQ@public.gmane.org_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])
> -ASQrhD/3864Qoru3DLDRmva12rvzsF7f@public.gmane.org(: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-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
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.