Skip to content

Commit

Permalink
Added code to persist sinatra cookies between requests
Browse files Browse the repository at this point in the history
  • Loading branch information
jferris committed Apr 2, 2009
1 parent aa90499 commit 33d5e56
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/webrat/sinatra.rb
Expand Up @@ -12,6 +12,7 @@ def initialize(context = nil)

app = context.respond_to?(:app) ? context.app : Sinatra::Application
@browser = Sinatra::TestHarness.new(app)
@cookies = []
end

%w(get head post put delete).each do |verb|
Expand All @@ -22,7 +23,9 @@ def #{verb}(path, data, headers = {})
data
end
headers["HTTP_HOST"] = "www.example.com"
headers["HTTP_COOKIE"] = @cookies.join(',')
@browser.#{verb}(path, params, headers)
set_cookies
end
RUBY
end
Expand All @@ -37,6 +40,12 @@ def response_code

private

def set_cookies
if set_cookie = @browser.response.headers['Set-Cookie']
@cookies << set_cookie
end
end

def response
@browser.response
end
Expand Down
31 changes: 31 additions & 0 deletions spec/integration/sinatra/cookies_app.rb
@@ -0,0 +1,31 @@
require 'rubygems'
require 'sinatra'

use_in_file_templates!

get "/get" do
erb :get, :locals => { :cookies => request.cookies }
end

get %r{/set/(.*)} do |key|
response.set_cookie(key, 'set')
redirect '/get'
end

__END__

@@ layout
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<title>sinatra cookie testing with webrat</title>
<body>
<%= yield %>
</body>
</html>

@@ get

one = <%= cookies['one'] %>
two = <%= cookies['two'] %>
<a href="/set/one">set one</a>
<a href="/set/two">set two</a>
13 changes: 13 additions & 0 deletions spec/integration/sinatra/test/cookies_app_test.rb
@@ -0,0 +1,13 @@
require File.dirname(__FILE__) + "/test_helper"
require File.dirname(__FILE__) + "/../cookies_app"

class MyCookiesAppTest < Test::Unit::TestCase
def test_cookies_persist
visit "/get"
click_link "set one"
assert response_body.include?('one = set'), response_body
click_link "set two"
assert response_body.include?('one = set'), response_body
assert response_body.include?('two = set'), response_body
end
end

0 comments on commit 33d5e56

Please sign in to comment.