{ 'foo' ...">

How to test a Sinatra application using a session

How to test a Sinatra application using a session?

get "/", {}, {'rack.session' =>  { 'foo' => 'blah' } }

This code does not work for me, I have "enable: sessions" in my application.

+3
source share
4 answers

It seems like the problem is to activate enable :sessions.

You must deactivate this option to be available to overwrite the session.

The solution may be:

# my_test.rb (first line, or at least before you require your 'my_app.rb')
ENV['RACK_ENV'] = 'test'

# my_app.rb (your sinatra application)
enable :sessions  unless test?

# my_test.rb (in your test block)
get '/', {}, 'rack.session' => { :key => 'value' }

On the other hand, in order to be able to check any session change that is expected in action, we can send not a hash to rack.session, but a pointer to a hash so that we can check after calling the action if the hash has changed:

# my_test.rb (in your test block)
session = {}
get '/', {}, 'rack.session' => session
assert_equal 'value', session[:key]
+4

, - , , @fguillen . , / , , , :

# in myapp_spec.rb
require 'rspec'
require 'rack/test'
require 'myapp'

it "should set the session params" do
  get 'users/current/projects', {}, 'rack.session' => {:user =>'1234'}
end

# in myapp.rb

enable :sessions

get 'users/current/projects' do
  p env['rack.session']
end
+2

As Philip suggested, it would be better to manually set the session variable before the get request.

session[:foo] = 'blah'
get "/"
-1
source

I finally figured this out by decapitation Rack::Test::Session:

https://gist.github.com/troelskn/5047135

-1
source

Source: https://habr.com/ru/post/1779480/


All Articles