Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rack doesn't support passing in sessions via the request anymore (Rack >= v1.0). <a href="http://web.archive.org/web/20111025134130/http://snippets.aktagon.com/snippets/332-Testing-sessions-with-Sinatra-and-Rack-Test" rel="nofollow">Read this post for more detailed information on that.</a></p> <p>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:</p> <pre><code>post '/set_sess_var/:id' session[:user_id] = params[:id] end </code></pre> <p>Let's pretend there's another route that you actually wanted to test which is using the session variable like this:</p> <pre><code>get '/get_user_attributes' User.find(session[:user_id]).attributes end </code></pre> <p>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:</p> <pre><code>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 </code></pre> <p>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):</p> <pre><code>def set_session_var(user_id) post '/set_sess_var/' + user_id end </code></pre> <p>and then call it in your tests when you needed it to be set:</p> <pre><code>it "should print out user attributes" do set_session_var(1) get '/get_user_attributes' last_response.body.should == User.find(1).attributes end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload