Skip to content
jsboulanger edited this page Jan 18, 2011 · 8 revisions

If you are finding issues when testing sessions, make sure you don’t use this:

enable :sessions

Call the Rack middleware directly (you’ll be able to set additional options, too):

use Rack::Session::Cookie

Classic style

App


require "sinatra"

get "/" do
  "Hello World"
end

Test


  require "rack/test"
  require "webrat"
  require "test/unit"

  Webrat.configure do |config|
    config.mode = :rack
  end

  class AppTest < Test::Unit::TestCase
    include Rack::Test::Methods
    include Webrat::Methods
    include Webrat::Matchers

    def app
      Sinatra::Application.new
    end

    def test_it_works
      visit "/"
      assert_contain("Hello world")
    end
  end

Modular style

App


class App < Sinatra::Default
  get "/" do
    "Hello World"
  end
end

Test


  require "rack/test"
  require "webrat"
  require "test/unit"

  Webrat.configure do |config|
    config.mode = :rack
  end

  class AppTest < Test::Unit::TestCase
    include Rack::Test::Methods
    include Webrat::Methods
    include Webrat::Matchers

    def app
      App.new
    end

    def test_it_works
      visit "/"
      assert_contain("Hello world")
    end
  end


Doing this with RSpec instead of Test::Unit (Classic style only, because that’s what my app is)

In the hope that it will save someone else from the headache figuring it out cost me :-)

my_app.rb


require 'sinatra'

get '/' do
  'Some text'
end

spec_helper.rb


require 'webrat'
require 'rack/test'

module MyHelpers
  def app
    Sinatra::Application
  end
end

Webrat.configure do |config|
  config.mode= :rack
end

RSpec.configure do |config|
  config.include Rack::Test::Methods
  config.include Webrat::Methods
  config.include Webrat::Matchers
  config.include MyHelpers
end


default_page_spec.rb


require File.dirname(__FILE__) + '/spec_helper'
require File.dirname(__FILE__) + '/../../my_app'

describe 'The default page' do
  it 'should have some text' do
    visit "/"
    response_body.should contain 'Some text'
  end
end


Modular style, with RSpec

App


require 'rubygems'
require 'sinatra/base'

class MyApp < Sinatra::Base
  get "/" do
    "Hello World"
  end
end

Test


  require "rack/test"
  require 'spec'
  require 'spec/autorun'
  require 'spec/interop/test'
  require 'webrat'

  Webrat.configure do |config|
    config.mode = :rack
  end

  module AppHelper
    def app
      MyApp
    end
  end

  RSpec.configure do |config|
    config.include Rack::Test::Methods
    config.include Webrat::Methods
    config.include Webrat::Matchers
    config.include AppHelper
  end

 describe MyApp do
  it "should respond to /" do
    visit "/"
  end