Tutorial :Test with Rspec using session sinatra


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

I using Rspec + sinatra



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  


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.


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »