Test with Rspec using session sinatra

北慕城南 提交于 2019-12-07 17:05:51

问题


I have sinatra appliction using session, how do I test a page that uses session?

I using Rspec + sinatra

Tks


回答1:


This page, show's the main problem of testing session with rspec and sinatra.

The main problem is that the variable session is not accessible from the test code. To solve it, it suggests (and I confirm) to add the fowling lines at spec/spec_helper.rb:

def session
  last_request.env['rack.session']
end

It will make accessible a mocked session object from the last request at the test code.

Here's my controller code that read's a code param and stores its value at session:

post '/step2callback' do
  session['code'] = params['code']
end

Then here's test code:

context "making an authentication" do
  before do
    post "/step2callback", code: "code_sample"
  end
  it "reads the param code and saves it at session" do
    expect(session['code']).to eq("code_sample")
  end  
end



回答2:


Same like all other pages.

You need to clarify your question. What is problem with testing session. If problems is that user need to be logged in, then you can use something like this in spec file:

before :each do
  post "/login", {:username => "myuser", :password => "mypass"}
end

which will log you in before each test.




回答3:


I was only able to get it to work by disabling sessions for the test environment. This blog post has a good example: http://benprew.posterous.com/testing-sessions-with-sinatra



来源:https://stackoverflow.com/questions/2434800/test-with-rspec-using-session-sinatra

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