测试使用 session 的 Sinatra 应用程序 [英] Testing a Sinatra application that uses session
问题描述
如何测试使用 session 的 Sinatra 应用程序?
How to test Sinatra application which is using session?
get "/", {}, {'rack.session' => { 'foo' => 'blah' } }
此代码对我不起作用,我的应用中有启用:会话".
This code doesn't work for me, I have 'enable :sessions' in my app.
推荐答案
看起来问题实际上是激活了 enable :sessions
.
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.
解决方案可能是:
# 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' }
另一方面,为了能够检查 action 预期执行的任何 session 更改,我们可以不发送 hash 到rack.session 但是一个指向散列的指针,所以我们可以在 action 调用之后检查 hash 是否有改变了:
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]
这篇关于测试使用 session 的 Sinatra 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!