How to test Sinatra app using session

我是研究僧i 提交于 2019-12-18 17:13:28

问题


How to test Sinatra application wich is using session?

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

This code doesn't work for me, I have 'enable :sessions' in my app.


回答1:


It looks like the problem is actually to have enable :sessions activated.

You have to deactivate this setting in order to be available to overwrite the session.

The solution could 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' }

In the other hand to be able to check any session change that the action is expected to do we can send not a hash to the rack.session but a pointer to a hash so we can check after the action call if the hash has changed:

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



回答2:


Just ran into this problem and the solution is simply the order of requiring the files, so @fguillen was correct. At the top of your spec, make sure you require rack/test before your sinatra app, so at a minimum, this should get you started:

# 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



回答3:


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

session[:foo] = 'blah'
get "/"



回答4:


I finally figured it out by monkey patching Rack::Test::Session:

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



来源:https://stackoverflow.com/questions/4402808/how-to-test-sinatra-app-using-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!