Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate a session variable in minitest?

I'm using Rails 5 and minitest. I want to test out a controller method that requires a login, validated by the filter in teh controller

  before_filter :require_current_user

    def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def require_current_user
    redirect_to(:root, :notice => "you must be logged in") unless current_user
  end

To simulates the session variable, I added this in my test

  def setup
    @logged_in_user = users(:one)
    session[:user_id] = @logged_in_user.id
  end

test "do create" do
  person = people(:one)
  rating
  post rate_url, params: {person_id: person.id, rating: rating}

  # Verify we got the proper response
  assert_response :success
end

But when I run the above test, it results in the error

NoMethodError: undefined method `session' for nil:NilClass
    test/controllers/rates_controller_test.rb:10:in `setup'

How do I simulate a session variable in minitest?

Edit: Per the response given, here is my session_create method

  def create
    puts "env: #{env["omniauth.auth"]}"
    user = User.from_omniauth(env["omniauth.auth"])
    first_login = user.last_login.nil?
    # Record the fact that this is their first login in the session
    session[:first_login] = first_login
    # Record the last login of the user
    user.last_login = Time.now
    user.save
    session[:user_id] = user.id

    last_page_visited = session[:last_page_visited]
    session.delete(:last_page_visited)
    url = last_page_visited.present? ? last_page_visited : url_for(:controller => 'votes', :action => 'index')
    redirect_to url
  end
like image 382
Dave Avatar asked Oct 29 '22 20:10

Dave


2 Answers

I think this will work for you.

controller.session[:user_id] = users(:one).id

Have a look at here
You can also post to your login page for each test and set session

post login_url, params: { params_necessory_for_login )

Checkout this

like image 132
Manishh Avatar answered Nov 14 '22 05:11

Manishh


In Rails 4.2 for ActionController::TestCase works:

@controller.session[:user_id] = users(:one).id

Maybe for Rails 5 will work too.

like image 36
faramund Avatar answered Nov 14 '22 03:11

faramund