Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra + Rack::Test + Rspec2 - Using Sessions?

It's the first time I'm working with Sinatra and I just can't get sessions to work in my tests. I have enable :sessions in my app.

I tried:

get "/controller/something", {}, "rack.session" => {:session => "Aa"}

or

get "/controller/something", {}, "session" => {:session => "Aa"}

But no session variables are being set in my request. I've looked around the web and tried several suggestions but nothing seems to work. Am I missing something?

Thanks!

like image 430
Denny Avatar asked Oct 10 '22 19:10

Denny


1 Answers

Rack doesn't support passing in sessions via the request anymore (Rack >= v1.0). Read this post for more detailed information on that.

The best way to set a session variable in your app is to call an action inside of your application that will set the session variable. For instance, if you have a route inside your app that sets a session variable like this:

post '/set_sess_var/:id'
  session[:user_id] = params[:id]
end

Let's pretend there's another route that you actually wanted to test which is using the session variable like this:

get '/get_user_attributes'
  User.find(session[:user_id]).attributes
end

Then in your tests, you should first call the route which sets the session, then go onto another route which uses it. Here is rspec notation, since that is what I use for testing:

it "should print out user attributes" do
  user_id = 1
  post '/set_sess_var/' + user_id
  get '/get_user_attributes'
  last_response.body.should == User.find(user_id).attributes
end

If you were going to be using the route frequently in your tests, then you could write a method to accomplish this in your test file (if you're using Rspec, then this method could go in your spec_helper.rb or in your controller_spec.rb file):

def set_session_var(user_id)
  post '/set_sess_var/' + user_id
end

and then call it in your tests when you needed it to be set:

it "should print out user attributes" do
  set_session_var(1)
  get '/get_user_attributes'
  last_response.body.should == User.find(1).attributes
end
like image 179
Batkins Avatar answered Oct 13 '22 10:10

Batkins