开发者

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 mi开发者_Python百科ssing something?

Thanks!


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


You need to use the keys that will end up in env:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜