Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined local variable or method 'session' in model test

I'm creating a Ruby on Rails application, and am trying to run a test involving my User model to see if the "Remember me" feature works. I'm using Rails' inbuilt cookies hash to store the cookies, and the session hash to store the current session. I've run various tests (integration, model, and controller) where I use the session variable, but for some reason in this particular case it isn't being recognized.

NameError: undefined local variable or method `session' for #<UserTest:0x0000000658b5c8>

The error happens in the else block in the log_in_as method below:

test_helper.rb

...

def log_in_as(user, options = {})
  password = options[:password] || 'password'
  remember_me = options[:remember_me] || '1'

  if integration_test?
    post login_path, session: { email: user.email, password: password, remember_me: remember_me }
  else
    session[:user_id] = user.id
  end
end

I call log_in_as in my User test; both of these tests fail.

user_test.rb

require 'test_helper'
...
test "login with remembering" do
  log_in_as(@user, remember_me: '1')
  assert_not_nil cookies['remember_token']
end

test "login without remembering" do
  log_in_as(@user, remember_me: '0')
  assert_nil cookies['remember_token']
end
...

And when I remove that line of code from the helper, an error is thrown saying that cookies isn't recognized. What is the issue here?

like image 719
sarangj Avatar asked Jul 14 '15 00:07

sarangj


1 Answers

The session hash isn't available in models, only in controllers and views and controller and view tests.

like image 111
p4sh4 Avatar answered Oct 28 '22 03:10

p4sh4