leifg
leifg

Reputation: 8988

Sinatra test with sessions and concurrent access

I wanted to write a little tests that concurrently accesses my little sinatra app.

The problem here is, that I use sessions (via Rack::Session::Pool). I could not figure out how to let rack-test spawn a new session. Whe I inject session data in my request, I always end up with one session. So I can basically have only 1 session at a time.

In my test I tried the following:

threads = []
2.times do |index|
  threads << Thread.new do
    get "/controller/something", {}, "rack.session" => {:id => "Thread#{index}"}
    post "/do_action"
  end
end
thrads.each{|t| t.join}

Is there some kind of "Browser-Layer where I can have multiple instances"?

EDIT: I am sorry I have to clarify: The threading example was just a wild guess to get a new session. It didn't work. So I'm just looking for a way to open multiple sessions on a runnin (test)server. In development mode I can just open a new browser session to achieve such a thing. In test mode I'm currently lost.

Upvotes: 1

Views: 825

Answers (1)

Dave Sag
Dave Sag

Reputation: 13486

Here's a working example using MiniTest with the Spec syntax extensions.

# using MiniTest::Spec extensions
# http://bfts.rubyforge.org/minitest/MiniTest/Spec.html

describe 'Fun with Sinatra and multiple sessions' do
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  it "does some stuff with multiple sessions" do
    sess1 = Rack::Test::Session.new(Rack::MockSession.new(app))
    sess2 = Rack::Test::Session.new(Rack::MockSession.new(app))
    sess1.wont_equal sess2

    sess1.get '/' # or whatever
    sess1.last_response.must_equal :ok?

    sess2.get '/' # or whatever
    sess2.last_response.must_equal :ok?
  end

  it "this does the same thing" do
    sess2 = Rack::Test::Session.new(Rack::MockSession.new(app))

    get '/' # or whatever
    last_response.must_equal :ok?

    sess2.get '/' # or whatever
    sess2.last_response.must_equal :ok?

  end

end

Upvotes: 1

Related Questions