Peterxwl
Peterxwl

Reputation: 1123

NoMethodError: undefined method `feed' for nil:NilClass

I am following the steps strictly of Ruby on Rails Tutorials by Michael Hartl now and I am stuck in Listing 11.45 of Chapter 11.3- Manipulating microposts. When I run rake test before next section 11.3.4-Destroying microposts, 5 errors appears with similar reasons. It is supposed to be green as tutorial claimed. I don't understand why and how to solve that. One of 5 errors is:

ERROR["test_login_with_invalid_information", UsersLoginTest, 2015-05-31 06:10:56 -0400] test_login_with_invalid_information#UsersLoginTest (1433067056.81s) NoMethodError: NoMethodError: undefined method 'feed' for nil:NilClass app/controllers/static_pages_controller.rb:4:in 'home' test/integration/users_login_test.rb:18:in 'block in class:UsersLoginTest'

In app/models/user.rb, the method 'feed' is as below:

 def feed
  Micropost.where("user_id = ?", id)
end

In app/controllers/static_pages_controller.rb, the code is as below:

def home
  if logged_in?
    @micropost  = current_user.microposts.build
    @feed_items = current_user.feed.paginate(page: params[:page])
  end
end

In test/integration/users_login_test.rb line 18:

test "login with invalid information" do
  get login_path
  assert_template 'sessions/new'
  post login_path, session: { email: "", password: "" }
  assert_template 'sessions/new'
  assert_not flash.empty?
  get root_path            <- line 18
  assert flash.empty?
end

Upvotes: 1

Views: 1012

Answers (2)

Lucas Cash Hlongwane
Lucas Cash Hlongwane

Reputation: 189

Replace:

@feed_items = current_user.feed.paginate(page: params[:page])

with:

@feed_items = current_user.feed.paginate(page: params[:page]) if logged_in?

Upvotes: 1

Agazoom
Agazoom

Reputation: 618

The error is happening on page which is the root_path.

current_user is not defined (is nil), so the method call current_user.feed in your controller is failing.

Somewhere in the code, as part of the authentication process, the value of current_user needs to be set. From experience this is usually done in application_controller.rb.

Are you sure these steps are not in the tutorial?

Upvotes: 2

Related Questions