How do I simulate a session variable in minitest?
Asked Answered
B

2

7

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
Bayles answered 23/1, 2018 at 2:54 Comment(3)
Please paste your test case here as wellEmelina
The code in teh "setup" method is what's in teh test taht's failing. I added the test itself although I want to simulate the session for every test, which is why I want to put the code in a setup method as opposed to each individual test.Bayles
Possible duplicate of Unable to set session hash in Rails 5 controller testCensor
B
2

In Rails 4.2 for ActionController::TestCase works:

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

Maybe for Rails 5 will work too.

By answered 17/1, 2019 at 9:40 Comment(0)
B
1

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

Barrybarrymore answered 23/1, 2018 at 4:52 Comment(1)
I changed "session[:user_id] = @logged_in_user.id" to "controller.session[:user_id] = @logged_in_user.id" but still got the error "NoMethodError: undefined method `session' for nil:NilClass". "session" is not specific to my controller though. It seems to be some global Rails application variable b/c I never declare it anywhere in my app.Bayles

© 2022 - 2024 — McMap. All rights reserved.