dimanche 3 janvier 2016

Rails - helper - ActionView::Template::Error:

my test gets the following error that I am struggling to understand.

1) Confirmations should display the form to add a confirmation
Failure/Error: <%= @current_user.name %>
 ActionView::Template::Error:
   undefined method `name' for nil:NilClass
 # ./app/views/shared/_navbaruser.html.erb:5:in `_app_views_shared__navbaruser_html_erb__199785411648297937_70206846667160'
 # ./app/views/confirmations/new.html.erb:5:in `_app_views_confirmations_new_html_erb__1859940191732947556_70206920673040'
 # ./spec/requests/confirmations_spec.rb:11:in `block (2 levels) in <top (required)>'
 # ------------------
 # --- Caused by: ---
 # NoMethodError:
 #   undefined method `name' for nil:NilClass
 #   ./app/views/shared/_navbaruser.html.erb:5:in `_app_views_shared__navbaruser_html_erb__199785411648297937_70206846667160'

The test is a simple test that verifies the response from the server

it 'should display the form to add a confirmation' do
  get new_confirmation_path
  expect(response).to be_success
  expect(response).to have_http_status(200)
end

current_user method is defined in my helper file as follows:

def current_user
if (user_id = session[:user_id])
  @current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
  user = User.find_by(id: user_id)
end

Note that I do not get any issue in my app and I do get the name of the current user when I call current_user.name in my view. I just want to get rid of the error when I run my tests.

My view calls a partial

<%= render 'shared/navbaruser' %>

The partial calls the name of the current user

<%= @current_user.name %>

Could anyone give me some hints to understand the error? I am struggling especially as the application works fine. Thanks.

Aucun commentaire:

Enregistrer un commentaire