Upaded to webrat newest

Signed-off-by: gaffo <mike@uberu.com>
This commit is contained in:
gaffo 2009-01-04 15:20:21 -06:00
commit 0f0dab0b0b
104 changed files with 1914 additions and 232 deletions

View File

@ -21,6 +21,7 @@
* Minor enhancements * Minor enhancements
* Added assert_contain, assert_not_contain [#86] (Mike Gaffney) * Added assert_contain, assert_not_contain [#86] (Mike Gaffney)
* Add configuration options for the Selenium environment and port (Kieran Pilkington)
* Maximize the browser window after initializing Selenium (Luke Melia) * Maximize the browser window after initializing Selenium (Luke Melia)
* Better inspect output for Webrat elements * Better inspect output for Webrat elements
* Sets the Webrat mode with Configuration#mode= in the config block [#85] (Mike Gaffney) * Sets the Webrat mode with Configuration#mode= in the config block [#85] (Mike Gaffney)

View File

@ -1,4 +1,4 @@
require 'rubygems' # require 'rubygems'
require "rake/gempackagetask" require "rake/gempackagetask"
require 'rake/rdoctask' require 'rake/rdoctask'
require "rake/clean" require "rake/clean"
@ -28,8 +28,8 @@ spec = Gem::Specification.new do |s|
s.extra_rdoc_files = %w(README.rdoc MIT-LICENSE.txt) s.extra_rdoc_files = %w(README.rdoc MIT-LICENSE.txt)
# Dependencies # Dependencies
s.add_dependency "nokogiri", ">= 1.0.6" s.add_dependency "nokogiri", ">= 1.1.0"
s.rubyforge_project = "webrat" s.rubyforge_project = "webrat"
end end
@ -52,13 +52,13 @@ end
desc "Run API and Core specs" desc "Run API and Core specs"
Spec::Rake::SpecTask.new do |t| Spec::Rake::SpecTask.new do |t|
t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""] t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
t.spec_files = FileList['spec/**/*_spec.rb'] t.spec_files = FileList['spec/public/**/*_spec.rb'] + FileList['spec/private/**/*_spec.rb']
end end
desc "Run all specs in spec directory with RCov" desc "Run all specs in spec directory with RCov"
Spec::Rake::SpecTask.new(:rcov) do |t| Spec::Rake::SpecTask.new(:rcov) do |t|
t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""] t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
t.spec_files = FileList['spec/**/*_spec.rb'] t.spec_files = FileList['spec/public/**/*_spec.rb'] + FileList['spec/private/**/*_spec.rb']
t.rcov = true t.rcov = true
t.rcov_opts = lambda do t.rcov_opts = lambda do
IO.readlines(File.dirname(__FILE__) + "/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten IO.readlines(File.dirname(__FILE__) + "/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
@ -71,8 +71,8 @@ end
desc 'Install the package as a gem.' desc 'Install the package as a gem.'
task :install_gem => [:clean, :package] do task :install_gem => [:clean, :package] do
gem = Dir['pkg/*.gem'].first gem_filename = Dir['pkg/*.gem'].first
sh "sudo gem install --local #{gem}" sh "sudo gem install --local #{gem_filename}"
end end
desc "Delete generated RDoc" desc "Delete generated RDoc"
@ -99,6 +99,33 @@ task :spec_deps do
end end
end end
task :prepare do
system "ln -s ../../../../.. ./spec/integration/rails/vendor/plugins/webrat"
end
namespace :spec do
desc "Run the integration specs"
task :integration => ["integration:rails", "integration:merb"]
namespace :integration do
desc "Run the Rails integration specs"
task :rails do
Dir.chdir "spec/integration/rails" do
result = system "rake test:integration"
raise "Tests failed" unless result
end
end
desc "Run the Merb integration specs"
task :merb do
Dir.chdir "spec/integration/merb" do
result = system "rake spec"
raise "Tests failed" unless result
end
end
end
end
task :default => :spec task :default => :spec
task :precommit => ["spec", "spec:jruby"] task :precommit => ["spec", "spec:jruby", "spec:integration"]

View File

@ -27,9 +27,17 @@ module Webrat
# Save and open pages with error status codes (500-599) in a browser? Defualts to true. # Save and open pages with error status codes (500-599) in a browser? Defualts to true.
attr_writer :open_error_files attr_writer :open_error_files
# Which environment should the selenium tests be run in? Defaults to selenium.
attr_accessor :selenium_environment
# Which port should the selenium tests be run on? Defaults to 3001.
attr_accessor :selenium_port
def initialize # :nodoc: def initialize # :nodoc:
self.open_error_files = true self.open_error_files = true
self.parse_with_nokogiri = !Webrat.on_java? self.parse_with_nokogiri = !Webrat.on_java?
self.selenium_environment = :selenium
self.selenium_port = 3001
end end
def parse_with_nokogiri? #:nodoc: def parse_with_nokogiri? #:nodoc:

View File

@ -8,7 +8,7 @@ module Webrat
# A page load or form submission returned an unsuccessful response code (500-599) # A page load or form submission returned an unsuccessful response code (500-599)
class PageLoadError < WebratError class PageLoadError < WebratError
end end
def self.session_class def self.session_class
case Webrat.configuration.mode case Webrat.configuration.mode
when :rails when :rails
@ -24,32 +24,41 @@ module Webrat
when :mechanize when :mechanize
MechanizeSession MechanizeSession
else else
raise WebratError.new("Unknown Webrat mode: #{Webrat.configuration.mode.inspect}") raise WebratError.new(<<-STR)
Unknown Webrat mode: #{Webrat.configuration.mode.inspect}
Please ensure you have a Webrat configuration block that specifies a mode
in your test_helper.rb, spec_helper.rb, or env.rb (for Cucumber).
For example:
Webrat.configure do |config|
config.mode = :rails
end
STR
end end
end end
class Session class Session
extend Forwardable extend Forwardable
include Logging include Logging
include SaveAndOpenPage include SaveAndOpenPage
attr_reader :current_url attr_reader :current_url
attr_reader :elements attr_reader :elements
def initialize(context = nil) #:nodoc: def initialize(context = nil) #:nodoc:
@http_method = :get @http_method = :get
@data = {} @data = {}
@default_headers = {} @default_headers = {}
@custom_headers = {} @custom_headers = {}
@context = context @context = context
reset reset
end end
def current_dom #:nodoc: def current_dom #:nodoc:
current_scope.dom current_scope.dom
end end
# For backwards compatibility -- removing in 1.0 # For backwards compatibility -- removing in 1.0
def current_page #:nodoc: def current_page #:nodoc:
page = OpenStruct.new page = OpenStruct.new
@ -58,7 +67,7 @@ module Webrat
page.data = @data page.data = @data
page page
end end
def doc_root #:nodoc: def doc_root #:nodoc:
nil nil
end end
@ -70,7 +79,7 @@ module Webrat
def http_accept(mime_type) def http_accept(mime_type)
header('Accept', Webrat::MIME.mime_type(mime_type)) header('Accept', Webrat::MIME.mime_type(mime_type))
end end
def basic_auth(user, pass) def basic_auth(user, pass)
encoded_login = ["#{user}:#{pass}"].pack("m*") encoded_login = ["#{user}:#{pass}"].pack("m*")
header('HTTP_AUTHORIZATION', "Basic #{encoded_login}") header('HTTP_AUTHORIZATION', "Basic #{encoded_login}")
@ -93,28 +102,34 @@ module Webrat
save_and_open_page if exception_caught? && Webrat.configuration.open_error_files? save_and_open_page if exception_caught? && Webrat.configuration.open_error_files?
raise PageLoadError.new("Page load was not successful (Code: #{response_code.inspect}):\n#{formatted_error}") unless success_code? raise PageLoadError.new("Page load was not successful (Code: #{response_code.inspect}):\n#{formatted_error}") unless success_code?
reset reset
@current_url = url @current_url = url
@http_method = http_method @http_method = http_method
@data = data @data = data
request_page(response.headers["Location"], :get, data) if redirect?
return response return response
end end
def success_code? #:nodoc: def success_code? #:nodoc:
(200..499).include?(response_code) (200..499).include?(response_code)
end end
def redirect? #:nodoc:
response_code / 100 == 3
end
def exception_caught? #:nodoc: def exception_caught? #:nodoc:
response_body =~ /Exception caught/ response_body =~ /Exception caught/
end end
def current_scope #:nodoc: def current_scope #:nodoc:
scopes.last || page_scope scopes.last || page_scope
end end
# Reloads the last page requested. Note that this will resubmit forms # Reloads the last page requested. Note that this will resubmit forms
# and their data. # and their data.
def reloads def reloads
@ -122,10 +137,10 @@ module Webrat
end end
webrat_deprecate :reload, :reloads webrat_deprecate :reload, :reloads
# Works like click_link, but only looks for the link text within a given selector # Works like click_link, but only looks for the link text within a given selector
# #
# Example: # Example:
# click_link_within "#user_12", "Vote" # click_link_within "#user_12", "Vote"
def click_link_within(selector, link_text) def click_link_within(selector, link_text)
@ -135,14 +150,14 @@ module Webrat
end end
webrat_deprecate :clicks_link_within, :click_link_within webrat_deprecate :clicks_link_within, :click_link_within
def within(selector) def within(selector)
scopes.push(Scope.from_scope(self, current_scope, selector)) scopes.push(Scope.from_scope(self, current_scope, selector))
ret = yield(current_scope) ret = yield(current_scope)
scopes.pop scopes.pop
return ret return ret
end end
# Issues a GET request for a page, follows any redirects, and verifies the final page # Issues a GET request for a page, follows any redirects, and verifies the final page
# load was successful. # load was successful.
# #
@ -151,7 +166,7 @@ module Webrat
def visit(url = nil, http_method = :get, data = {}) def visit(url = nil, http_method = :get, data = {})
request_page(url, http_method, data) request_page(url, http_method, data)
end end
webrat_deprecate :visits, :visit webrat_deprecate :visits, :visit
# Subclasses can override this to show error messages without html # Subclasses can override this to show error messages without html
@ -166,25 +181,25 @@ module Webrat
def page_scope #:nodoc: def page_scope #:nodoc:
@_page_scope ||= Scope.from_page(self, response, response_body) @_page_scope ||= Scope.from_page(self, response, response_body)
end end
def dom def dom
page_scope.dom page_scope.dom
end end
def xml_content_type? def xml_content_type?
false false
end end
def simulate def simulate
return if Webrat.configuration.mode == :selenium return if Webrat.configuration.mode == :selenium
yield yield
end end
def automate def automate
return unless Webrat.configuration.mode == :selenium return unless Webrat.configuration.mode == :selenium
yield yield
end end
def_delegators :current_scope, :fill_in, :fills_in def_delegators :current_scope, :fill_in, :fills_in
def_delegators :current_scope, :set_hidden_field def_delegators :current_scope, :set_hidden_field
def_delegators :current_scope, :submit_form def_delegators :current_scope, :submit_form
@ -199,15 +214,13 @@ module Webrat
def_delegators :current_scope, :click_area, :clicks_area def_delegators :current_scope, :click_area, :clicks_area
def_delegators :current_scope, :click_link, :clicks_link def_delegators :current_scope, :click_link, :clicks_link
def_delegators :current_scope, :click_button, :clicks_button def_delegators :current_scope, :click_button, :clicks_button
def_delegators :current_scope, :should_see
def_delegators :current_scope, :should_not_see
def_delegators :current_scope, :field_labeled def_delegators :current_scope, :field_labeled
def_delegators :current_scope, :field_by_xpath def_delegators :current_scope, :field_by_xpath
def_delegators :current_scope, :field_with_id def_delegators :current_scope, :field_with_id
def_delegators :current_scope, :select_option def_delegators :current_scope, :select_option
private private
def reset def reset
@elements = {} @elements = {}
@_scopes = nil @_scopes = nil

View File

@ -42,11 +42,6 @@ module Webrat
:params => (data && data.any?) ? data : nil, :params => (data && data.any?) ? data : nil,
:headers => headers, :headers => headers,
:method => method) :method => method)
follow_redirect
end
def follow_redirect
self.get(@response.headers['Location'], nil, @response.headers) if @response.status == 302
end end
end end
@ -59,10 +54,6 @@ module Merb #:nodoc:
@_webrat_session ||= Webrat::MerbSession.new @_webrat_session ||= Webrat::MerbSession.new
@_webrat_session.response = @_webrat_session.request(uri, env) @_webrat_session.response = @_webrat_session.request(uri, env)
end end
def follow_redirect
@_webrat_session.follow_redirect
end
end end
end end
end end

View File

@ -9,51 +9,50 @@ module Webrat
def doc_root def doc_root
File.expand_path(File.join(RAILS_ROOT, 'public')) File.expand_path(File.join(RAILS_ROOT, 'public'))
end end
def saved_page_dir def saved_page_dir
File.expand_path(File.join(RAILS_ROOT, "tmp")) File.expand_path(File.join(RAILS_ROOT, "tmp"))
end end
def get(url, data, headers = nil) def get(url, data, headers = nil)
do_request(:get, url, data, headers) do_request(:get, url, data, headers)
end end
def post(url, data, headers = nil) def post(url, data, headers = nil)
do_request(:post, url, data, headers) do_request(:post, url, data, headers)
end end
def put(url, data, headers = nil) def put(url, data, headers = nil)
do_request(:put, url, data, headers) do_request(:put, url, data, headers)
end end
def delete(url, data, headers = nil) def delete(url, data, headers = nil)
do_request(:delete, url, data, headers) do_request(:delete, url, data, headers)
end end
def response_body def response_body
response.body response.body
end end
def response_code def response_code
response.code.to_i response.code.to_i
end end
def xml_content_type? def xml_content_type?
response.headers["Content-Type"].to_s =~ /xml/ response.headers["Content-Type"].to_s =~ /xml/
end end
protected protected
def integration_session def integration_session
@context @context
end end
def do_request(http_method, url, data, headers) #:nodoc: def do_request(http_method, url, data, headers) #:nodoc:
update_protocol(url) update_protocol(url)
url = normalize_url(url) integration_session.send(http_method, normalize_url(url), data, headers)
integration_session.request_via_redirect(http_method, url, data, headers)
end end
# remove protocol, host and anchor # remove protocol, host and anchor
def normalize_url(href) #:nodoc: def normalize_url(href) #:nodoc:
uri = URI.parse(href) uri = URI.parse(href)
@ -63,7 +62,7 @@ module Webrat
end end
normalized_url normalized_url
end end
def update_protocol(href) #:nodoc: def update_protocol(href) #:nodoc:
if href =~ /^https:/ if href =~ /^https:/
integration_session.https!(true) integration_session.https!(true)
@ -71,23 +70,15 @@ module Webrat
integration_session.https!(false) integration_session.https!(false)
end end
end end
def response #:nodoc: def response #:nodoc:
integration_session.response integration_session.response
end end
end end
end end
module ActionController #:nodoc: module ActionController #:nodoc:
module Integration #:nodoc:
Session.class_eval do
unless instance_methods.include?("put_via_redirect")
require "webrat/rails/redirect_actions"
include Webrat::RedirectActions
end
end
end
IntegrationTest.class_eval do IntegrationTest.class_eval do
include Webrat::Methods include Webrat::Methods
include Webrat::Matchers include Webrat::Matchers

View File

@ -1,18 +0,0 @@
# For Rails before http://dev.rubyonrails.org/ticket/10497 was committed
module Webrat
module RedirectActions #:nodoc:
def put_via_redirect(path, parameters = {}, headers = {})
put path, parameters, headers
follow_redirect! while redirect?
status
end
def delete_via_redirect(path, parameters = {}, headers = {})
delete path, parameters, headers
follow_redirect! while redirect?
status
end
end
end

View File

@ -26,8 +26,8 @@ module Webrat
def self.start_app_server #:nodoc: def self.start_app_server #:nodoc:
pid_file = File.expand_path(RAILS_ROOT + "/tmp/pids/mongrel_selenium.pid") pid_file = File.expand_path(RAILS_ROOT + "/tmp/pids/mongrel_selenium.pid")
system("mongrel_rails start -d --chdir=#{RAILS_ROOT} --port=3001 --environment=selenium --pid #{pid_file} &") system("mongrel_rails start -d --chdir=#{RAILS_ROOT} --port=#{Webrat.configuration.selenium_port} --environment=#{Webrat.configuration.selenium_environment} --pid #{pid_file} &")
TCPSocket.wait_for_service :host => "0.0.0.0", :port => 3001 TCPSocket.wait_for_service :host => "0.0.0.0", :port => Webrat.configuration.selenium_port.to_i
end end
def self.stop_app_server #:nodoc: def self.stop_app_server #:nodoc:

View File

@ -11,9 +11,7 @@ module Webrat
path, data, headers = *args path, data, headers = *args
params = data.merge({:env => headers || {}}) params = data.merge({:env => headers || {}})
self.__send__("#{verb}_it", path, params) self.__send__("#{verb}_it", path, params)
follow! while @response.redirect?
end end
end end
end end
end end

View File

@ -2,33 +2,33 @@ module Webrat #:nodoc:
def self.session_class #:nodoc: def self.session_class #:nodoc:
TestSession TestSession
end end
class TestSession < Session #:nodoc: class TestSession < Session #:nodoc:
attr_accessor :response_body attr_accessor :response_body
attr_writer :response_code attr_writer :response_code
def doc_root def doc_root
File.expand_path(File.join(".", "public")) File.expand_path(File.join(".", "public"))
end end
def response def response
@response ||= Object.new @response ||= Object.new
end end
def response_code def response_code
@response_code || 200 @response_code || 200
end end
def get(url, data) def get(url, data, headers = nil)
end end
def post(url, data) def post(url, data, headers = nil)
end end
def put(url, data) def put(url, data, headers = nil)
end end
def delete(url, data) def delete(url, data, headers = nil)
end end
end end
end end

21
spec/integration/merb/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
.DS_Store
log/*
tmp/*
TAGS
*~
.#*
schema/schema.rb
schema/*_structure.sql
schema/*.sqlite3
schema/*.sqlite
schema/*.db
*.sqlite
*.sqlite3
*.db
src/*
.hgignore
.hg/*
.svn/*
gems/gems/*
gems/specifications/*
merb_profile_results

View File

@ -0,0 +1,35 @@
require 'rubygems'
require 'rake/rdoctask'
require 'merb-core'
require 'merb-core/tasks/merb'
include FileUtils
# Load the basic runtime dependencies; this will include
# any plugins and therefore plugin rake tasks.
init_env = ENV['MERB_ENV'] || 'rake'
Merb.load_dependencies(:environment => init_env)
# Get Merb plugins and dependencies
Merb::Plugins.rakefiles.each { |r| require r }
# Load any app level custom rakefile extensions from lib/tasks
tasks_path = File.join(File.dirname(__FILE__), "lib", "tasks")
rake_files = Dir["#{tasks_path}/*.rake"]
rake_files.each{|rake_file| load rake_file }
desc "Start runner environment"
task :merb_env do
Merb.start_environment(:environment => init_env, :adapter => 'runner')
end
require 'spec/rake/spectask'
require 'merb-core/test/tasks/spectasks'
desc 'Default: run spec examples'
task :default => 'spec'
##############################################################################
# ADD YOUR CUSTOM TASKS IN /lib/tasks
# NAME YOUR RAKE FILES file_name.rake
##############################################################################

View File

@ -0,0 +1,2 @@
class Application < Merb::Controller
end

View File

@ -0,0 +1,13 @@
class Exceptions < Merb::Controller
# handle NotFound exceptions (404)
def not_found
render :format => :html
end
# handle NotAcceptable exceptions (406)
def not_acceptable
render :format => :html
end
end

View File

@ -0,0 +1,14 @@
class Testing < Application
def show_form
render
end
def submit_form
end
def redirect_to_root
redirect "/"
end
end

View File

@ -0,0 +1,63 @@
<div id="container">
<div id="header-container">
<img src="/images/merb.jpg" />
<!-- <h1>Mongrel + Erb</h1> -->
<h2>pocket rocket web framework</h2>
<hr />
</div>
<div id="left-container">
<h3>Exception:</h3>
<p><%= request.exceptions.first.message %></p>
</div>
<div id="main-container">
<h3>Why am I seeing this page?</h3>
<p>Merb couldn't find an appropriate content_type to return,
based on what you said was available via provides() and
what the client requested.</p>
<h3>How to add a mime-type</h3>
<pre><code>
Merb.add_mime_type :pdf, :to_pdf, %w[application/pdf], &quot;Content-Encoding&quot; =&gt; &quot;gzip&quot;
</code></pre>
<h3>What this means is:</h3>
<ul>
<li>Add a mime-type for :pdf</li>
<li>Register the method for converting objects to PDF as <code>#to_pdf</code>.</li>
<li>Register the incoming mime-type "Accept" header as <code>application/pdf</code>.</li>
<li>Specify a new header for PDF types so it will set <code>Content-Encoding</code> to gzip.</li>
</ul>
<h3>You can then do:</h3>
<pre><code>
class Foo &lt; Application
provides :pdf
end
</code></pre>
<h3>Where can I find help?</h3>
<p>If you have any questions or if you can't figure something out, please take a
look at our <a href="http://merbivore.com/"> project page</a>,
feel free to come chat at irc.freenode.net, channel #merb,
or post to <a href="http://groups.google.com/group/merb">merb mailing list</a>
on Google Groups.</p>
<h3>What if I've found a bug?</h3>
<p>If you want to file a bug or make your own contribution to Merb,
feel free to register and create a ticket at our
<a href="http://merb.lighthouseapp.com/">project development page</a>
on Lighthouse.</p>
<h3>How do I edit this page?</h3>
<p>You can change what people see when this happens by editing <tt>app/views/exceptions/not_acceptable.html.erb</tt>.</p>
</div>
<div id="footer-container">
<hr />
<div class="left"></div>
<div class="right">&copy; 2008 the merb dev team</div>
<p>&nbsp;</p>
</div>
</div>

View File

@ -0,0 +1,47 @@
<div id="container">
<div id="header-container">
<img src="/images/merb.jpg" />
<!-- <h1>Mongrel + Erb</h1> -->
<h2>pocket rocket web framework</h2>
<hr />
</div>
<div id="left-container">
<h3>Exception:</h3>
<p><%= request.exceptions.first.message %></p>
</div>
<div id="main-container">
<h3>Welcome to Merb!</h3>
<p>Merb is a light-weight MVC framework written in Ruby. We hope you enjoy it.</p>
<h3>Where can I find help?</h3>
<p>If you have any questions or if you can't figure something out, please take a
look at our <a href="http://merbivore.com/"> project page</a>,
feel free to come chat at irc.freenode.net, channel #merb,
or post to <a href="http://groups.google.com/group/merb">merb mailing list</a>
on Google Groups.</p>
<h3>What if I've found a bug?</h3>
<p>If you want to file a bug or make your own contribution to Merb,
feel free to register and create a ticket at our
<a href="http://merb.lighthouseapp.com/">project development page</a>
on Lighthouse.</p>
<h3>How do I edit this page?</h3>
<p>You're seeing this page because you need to edit the following files:
<ul>
<li>config/router.rb <strong><em>(recommended)</em></strong></li>
<li>app/views/exceptions/not_found.html.erb <strong><em>(recommended)</em></strong></li>
<li>app/views/layout/application.html.erb <strong><em>(change this layout)</em></strong></li>
</ul>
</p>
</div>
<div id="footer-container">
<hr />
<div class="left"></div>
<div class="right">&copy; 2008 the merb dev team</div>
<p>&nbsp;</p>
</div>
</div>

View File

@ -0,0 +1,12 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
<title>Fresh Merb App</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="/stylesheets/master.css" type="text/css" media="screen" charset="utf-8" />
</head>
<body>
<%#= message[:notice] %>
<%= catch_content :for_layout %>
</body>
</html>

View File

@ -0,0 +1,22 @@
<h1>Webrat Form</h1>
<form action="/testing/submit_form" method="post">
<label>
Text field
<input type="text" name="text_field" />
</label>
<label>
TOS <input type="checkbox" name="tos" />
</label>
<label>
Month
<select name="month">
<option>None</option>
<option>January</option>
</select>
</label>
<input type="submit" value="Test">
</form>

View File

@ -0,0 +1,15 @@
Merb.logger.info("Loaded DEVELOPMENT Environment...")
Merb::Config.use { |c|
c[:exception_details] = true
c[:reload_templates] = true
c[:reload_classes] = true
c[:reload_time] = 0.5
c[:ignore_tampered_cookies] = true
c[:log_auto_flush ] = true
c[:log_level] = :debug
c[:log_stream] = STDOUT
c[:log_file] = nil
# Or redirect logging into a file:
# c[:log_file] = Merb.root / "log" / "development.log"
}

View File

@ -0,0 +1,11 @@
Merb.logger.info("Loaded RAKE Environment...")
Merb::Config.use { |c|
c[:exception_details] = true
c[:reload_classes] = false
c[:log_auto_flush ] = true
c[:log_stream] = STDOUT
c[:log_file] = nil
# Or redirect logging into a file:
# c[:log_file] = Merb.root / "log" / "development.log"
}

View File

@ -0,0 +1,14 @@
require File.dirname(__FILE__) + "/../../../../../lib/webrat"
Merb.logger.info("Loaded TEST Environment...")
Merb::Config.use { |c|
c[:testing] = true
c[:exception_details] = true
c[:log_auto_flush ] = true
# log less in testing environment
c[:log_level] = :error
#c[:log_file] = Merb.root / "log" / "test.log"
# or redirect logger using IO handle
c[:log_stream] = STDOUT
}

View File

@ -0,0 +1,25 @@
# Go to http://wiki.merbivore.com/pages/init-rb
# Specify a specific version of a dependency
# dependency "RedCloth", "> 3.0"
# use_orm :none
use_test :rspec
use_template_engine :erb
Merb::Config.use do |c|
c[:use_mutex] = false
c[:session_store] = 'cookie' # can also be 'memory', 'memcache', 'container', 'datamapper
# cookie session store configuration
c[:session_secret_key] = 'adb9ea7a0e94b5513503f58623a393c5efe18851' # required for cookie session store
c[:session_id_key] = '_merb_session_id' # cookie session id key, defaults to "_session_id"
end
Merb::BootLoader.before_app_loads do
# This will get executed after dependencies have been loaded but before your app's classes have loaded.
end
Merb::BootLoader.after_app_loads do
# This will get executed after your app's classes have been loaded.
end

View File

@ -0,0 +1,11 @@
# use PathPrefix Middleware if :path_prefix is set in Merb::Config
if prefix = ::Merb::Config[:path_prefix]
use Merb::Rack::PathPrefix, prefix
end
# comment this out if you are running merb behind a load balancer
# that serves static files
use Merb::Rack::Static, Merb.dir_for(:public)
# this is our main merb application
run Merb::Rack::Application.new

View File

@ -0,0 +1,32 @@
# Merb::Router is the request routing mapper for the merb framework.
#
# You can route a specific URL to a controller / action pair:
#
# match("/contact").
# to(:controller => "info", :action => "contact")
#
# You can define placeholder parts of the url with the :symbol notation. These
# placeholders will be available in the params hash of your controllers. For example:
#
# match("/books/:book_id/:action").
# to(:controller => "books")
#
# Or, use placeholders in the "to" results for more complicated routing, e.g.:
#
# match("/admin/:module/:controller/:action/:id").
# to(:controller => ":module/:controller")
#
# You can specify conditions on the placeholder by passing a hash as the second
# argument of "match"
#
# match("/registration/:course_name", :course_name => /^[a-z]{3,5}-\d{5}$/).
# to(:controller => "registration")
#
# You can also use regular expressions, deferred routes, and many other options.
# See merb/specs/merb/router.rb for a fairly complete usage sample.
Merb.logger.info("Compiling routes...")
Merb::Router.prepare do
match("/").to(:controller => "testing", :action => "show_form")
match("/redirect").to(:controller => "testing", :action => "redirect_to_root")
end

View File

@ -0,0 +1 @@
--color

View File

@ -0,0 +1,24 @@
require "rubygems"
# Add the local gems dir if found within the app root; any dependencies loaded
# hereafter will try to load from the local gems before loading system gems.
if (local_gem_dir = File.join(File.dirname(__FILE__), '..', 'gems')) && $BUNDLE.nil?
$BUNDLE = true; Gem.clear_paths; Gem.path.unshift(local_gem_dir)
end
require "merb-core"
require "spec" # Satisfies Autotest and anyone else not using the Rake tasks
# this loads all plugins required in your init file so don't add them
# here again, Merb will do it for you
Merb.start_environment(:testing => true, :adapter => 'runner', :environment => ENV['MERB_ENV'] || 'test')
Spec::Runner.configure do |config|
config.include(Merb::Test::ViewHelper)
config.include(Merb::Test::RouteHelper)
config.include(Merb::Test::ControllerHelper)
end
Webrat.configure do |config|
config.mode = :merb
end

View File

@ -0,0 +1,21 @@
require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper"))
describe "Webrat" do
it "should visit pages" do
response = visit "/"
response.should contain("Webrat Form")
end
it "should submit forms" do
visit "/"
fill_in "Text field", :with => "Hello"
check "TOS"
select "January"
click_button "Test"
end
it "should follow redirects" do
response = visit "/redirect"
response.should contain("Webrat Form")
end
end

View File

@ -0,0 +1,31 @@
#!/usr/bin/env ruby
# This was added by Merb's bundler
require "rubygems"
require File.join(File.dirname(__FILE__), "common")
gems_dir = File.join(File.dirname(__FILE__), '..', 'gems')
if File.directory?(gems_dir)
$BUNDLE = true
Gem.clear_paths
Gem.path.replace([File.expand_path(gems_dir)])
ENV["PATH"] = "#{File.dirname(__FILE__)}:#{ENV["PATH"]}"
gem_file = File.join(gems_dir, "specifications", "<%= spec.name %>-*.gemspec")
if local_gem = Dir[gem_file].last
version = File.basename(local_gem)[/-([\.\d]+)\.gemspec$/, 1]
end
end
version ||= "<%= Gem::Requirement.default %>"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem '<%= @spec.name %>', version
load '<%= bin_file_name %>'

View File

@ -0,0 +1,64 @@
# This was added via Merb's bundler
require "rubygems"
require "rubygems/source_index"
module Gem
BUNDLED_SPECS = File.join(Dir.pwd, "gems", "specifications")
MAIN_INDEX = Gem::SourceIndex.from_gems_in(BUNDLED_SPECS)
FALLBACK_INDEX = Gem::SourceIndex.from_installed_gems
def self.source_index
MultiSourceIndex.new
end
def self.searcher
MultiPathSearcher.new
end
class ArbitrarySearcher < GemPathSearcher
def initialize(source_index)
@source_index = source_index
super()
end
def init_gemspecs
@source_index.map { |_, spec| spec }.sort { |a,b|
(a.name <=> b.name).nonzero? || (b.version <=> a.version)
}
end
end
class MultiPathSearcher
def initialize
@main_searcher = ArbitrarySearcher.new(MAIN_INDEX)
@fallback_searcher = ArbitrarySearcher.new(FALLBACK_INDEX)
end
def find(path)
try = @main_searcher.find(path)
return try if try
@fallback_searcher.find(path)
end
def find_all(path)
try = @main_searcher.find_all(path)
return try unless try.empty?
@fallback_searcher.find_all(path)
end
end
class MultiSourceIndex
def search(*args)
try = MAIN_INDEX.search(*args)
return try unless try.empty?
FALLBACK_INDEX.search(*args)
end
def find_name(*args)
try = MAIN_INDEX.find_name(*args)
return try unless try.empty?
FALLBACK_INDEX.find_name(*args)
end
end
end

View File

@ -0,0 +1,124 @@
require "erb"
Gem.pre_install_hooks.push(proc do |installer|
$INSTALLING << installer.spec
unless File.file?(installer.bin_dir / "common.rb")
FileUtils.mkdir_p(installer.bin_dir)
FileUtils.cp(File.dirname(__FILE__) / "common.rb", installer.bin_dir / "common.rb")
end
include ColorfulMessages
name = installer.spec.name
if $GEMS && versions = ($GEMS.assoc(name) || [])[1]
dep = Gem::Dependency.new(name, versions)
unless dep.version_requirements.satisfied_by?(installer.spec.version)
error "Cannot install #{installer.spec.full_name} " \
"for #{$INSTALLING.map {|x| x.full_name}.join(", ")}; " \
"you required #{dep}"
::Thor::Tasks::Merb::Gem.rollback_trans
exit!
end
end
success "Installing #{installer.spec.full_name}"
end)
class ::Gem::Uninstaller
def self._with_silent_ui
ui = Gem::DefaultUserInteraction.ui
def ui.say(str)
puts "- #{str}"
end
yield
class << Gem::DefaultUserInteraction.ui
remove_method :say
end
end
def self._uninstall(source_index, name, op, version)
unless source_index.find_name(name, "#{op} #{version}").empty?
uninstaller = Gem::Uninstaller.new(
name,
:version => "#{op} #{version}",
:install_dir => Dir.pwd / "gems",
:all => true,
:ignore => true
)
_with_silent_ui { uninstaller.uninstall }
end
end
def self._uninstall_others(source_index, name, version)
_uninstall(source_index, name, "<", version)
_uninstall(source_index, name, ">", version)
end
end
Gem.post_install_hooks.push(proc do |installer|
$INSTALLING.pop
source_index = installer.instance_variable_get("@source_index")
::Gem::Uninstaller._uninstall_others(
source_index, installer.spec.name, installer.spec.version
)
end)
class ::Gem::DependencyInstaller
alias old_fg find_gems_with_sources
def find_gems_with_sources(dep)
if @source_index.any? { |_, installed_spec|
installed_spec.satisfies_requirement?(dep)
}
return []
end
old_fg(dep)
end
end
class ::Gem::SpecFetcher
alias old_fetch fetch
def fetch(dependency, all = false, matching_platform = true)
idx = Gem::SourceIndex.from_installed_gems
dep = idx.search(dependency).sort.last
if dep
file = dep.loaded_from.dup
file.gsub!(/specifications/, "cache")
file.gsub!(/gemspec$/, "gem")
spec = ::Gem::Format.from_file_by_path(file).spec
[[spec, file]]
else
old_fetch(dependency, all, matching_platform)
end
end
end
class ::Gem::Installer
def app_script_text(bin_file_name)
template = File.read(File.dirname(__FILE__) / "app_script.rb")
erb = ERB.new(template)
erb.result(binding)
end
end
class ::Gem::Specification
def recursive_dependencies(from, index = Gem.source_index)
specs = self.runtime_dependencies.map do |dep|
spec = index.search(dep).last
unless spec
from_name = from.is_a?(::Gem::Specification) ? from.full_name : from.to_s
wider_net = index.find_name(dep.name).last
ThorUI.error "Needed #{dep} for #{from_name}, but could not find it"
ThorUI.error "Found #{wider_net.full_name}" if wider_net
::Thor::Tasks::Merb::Gem.rollback_trans
end
spec
end
specs + specs.map {|s| s.recursive_dependencies(self, index)}.flatten.uniq
end
end

View File

@ -0,0 +1,150 @@
require "rubygems"
require "rubygems/source_index"
require "rubygems/dependency_installer"
require "rubygems/uninstaller"
require "fileutils"
require File.join(File.dirname(__FILE__), "utils")
require File.join(File.dirname(__FILE__), "gem_ext")
require File.join(File.dirname(__FILE__), "ops")
$INSTALLING = []
module Merb
class Gem < Thor
extend ColorfulMessages
def initialize
dirs = [Dir.pwd, File.dirname(__FILE__) / ".."]
root = dirs.find {|d| File.file?(d / "config" / "dependencies.rb")}
if root
@depsrb = root / "config" / "dependencies.rb"
else
self.class.error "dependencies.rb was not found"
exit!
end
FileUtils.mkdir_p(Dir.pwd / "gems")
@list = Collector.collect(File.read(@depsrb))
@idx = ::Gem::SourceIndex.new.load_gems_in("gems/specifications")
end
def list
require "pp"
pp @list
end
desc "redeploy", "Syncs up gems/cache with gems/gems. All gems in the cache " \
"that are not already installed will be installed from the " \
"cache. All installed gems that are not in the cache will " \
"be uninstalled."
def redeploy
gem_dir = Dir.pwd / "gems" / "gems"
cache_dir = Dir.pwd / "gems" / "cache"
gems = Dir[gem_dir / "*"].map! {|n| File.basename(n)}
cache = Dir[cache_dir / "*.gem"].map! {|n| File.basename(n, ".gem")}
new_gems = cache - gems
outdated = gems - cache
idx = ::Gem::SourceIndex.new
idx.load_gems_in(Dir.pwd / "gems" / "specifications")
new_gems.each do |g|
installer = ::Gem::Installer.new(cache_dir / "#{g}.gem",
:bin_dir => Dir.pwd / "bin",
:install_dir => Dir.pwd / "gems",
:ignore_dependencies => true,
:user_install => false,
:wrappers => true,
:source_index => idx)
installer.install
end
outdated.each do |g|
/(.*)\-(.*)/ =~ g
name, version = $1, $2
uninstaller = ::Gem::Uninstaller.new(name,
:version => version,
:bin_dir => Dir.pwd / "bin",
:install_dir => Dir.pwd / "gems",
:ignore => true,
:executables => true
)
uninstaller.uninstall
end
end
desc "confirm", "Confirm the current setup. merb:gem:install will " \
"automatically run this task before committing the " \
"changes it makes."
def confirm(gems = @list)
::Gem.path.replace([Dir.pwd / "gems"])
::Gem.source_index.load_gems_in(Dir.pwd / "gems" / "specifications")
self.class.info "Confirming configuration..."
::Gem.loaded_specs.clear
begin
gems.each do |name, versions|
versions ||= []
::Gem.activate name, *versions
end
rescue ::Gem::LoadError => e
self.class.error "Configuration could not be confirmed: #{e.message}"
self.class.rollback_trans
end
self.class.info "Confirmed"
end
desc 'install', 'Sync up your bundled gems with the list in config/dependencies.rb'
def install(*gems)
if gems.empty?
gems = @list
else
gems = gems.map {|desc| name, *versions = desc.split(" ") }
end
$GEMS = gems
self.class.begin_trans
gems.each do |name, versions|
dep = ::Gem::Dependency.new(name, versions || [])
unless @idx.search(dep).empty?
next
end
rescue_failures do
$INSTALLING = []
_install(dep)
end
end
gem_dir = Dir.pwd / "gems" / "gems"
installed_gems = Dir[gem_dir / "*"].map! {|n| File.basename(n)}
list = full_list.map {|x| x.full_name}.compact
(installed_gems - list).each do |g|
/^(.*)\-(.*)$/ =~ g
name, version = $1, $2
uninstaller = ::Gem::Uninstaller.new(name,
:version => version,
:bin_dir => (Dir.pwd / "bin").to_s,
:install_dir => (Dir.pwd / "gems").to_s,
:ignore => true,
:executables => true
)
uninstaller.uninstall
end
confirm(gems)
self.class.commit_trans
end
end
end

View File

@ -0,0 +1,93 @@
module Thor::Tasks
module Merb
class Collector
attr_reader :dependencies
def self.collect(str)
collector = new
collector.instance_eval(str)
collector.dependencies
end
def initialize
@dependencies = []
end
def dependency(name, *versions)
versions.pop if versions.last.is_a?(Hash)
@dependencies << [name, versions]
end
end
class Gem < Thor
def full_list
@idx.load_gems_in("gems/specifications")
@list.map do |name, versions|
dep = ::Gem::Dependency.new(name, versions)
spec = @idx.search(dep).last
unless spec
self.class.error "A required dependency #{dep} was not found"
self.class.rollback_trans
end
deps = spec.recursive_dependencies(dep, @idx)
[spec] + deps
end.flatten.uniq
end
def rescue_failures(error = StandardError, prc = nil)
begin
yield
rescue error => e
if prc
prc.call(e)
else
puts e.message
puts e.backtrace
end
self.class.rollback_trans
end
end
def self.begin_trans
note "Beginning transaction"
FileUtils.cp_r(Dir.pwd / "gems", Dir.pwd / ".original_gems")
end
def self.commit_trans
note "Committing transaction"
FileUtils.rm_rf(Dir.pwd / ".original_gems")
end
def self.rollback_trans
if File.exist?(Dir.pwd / ".original_gems")
note "Rolling back transaction"
FileUtils.rm_rf(Dir.pwd / "gems")
FileUtils.mv(Dir.pwd / ".original_gems", Dir.pwd / "gems")
end
exit!
end
private
def _install(dep)
@idx.load_gems_in("gems/specifications")
return if @idx.search(dep).last
installer = ::Gem::DependencyInstaller.new(
:bin_dir => Dir.pwd / "bin",
:install_dir => Dir.pwd / "gems",
:user_install => false)
begin
installer.install dep.name, dep.version_requirements
rescue ::Gem::GemNotFoundException => e
puts "Cannot find #{dep}"
rescue ::Gem::RemoteFetcher::FetchError => e
puts e.message
puts "Retrying..."
retry
end
end
end
end
end

View File

@ -0,0 +1,40 @@
class String
def /(other)
(Pathname.new(self) + other).to_s
end
end
module ColorfulMessages
# red
def error(*messages)
puts messages.map { |msg| "\033[1;31m#{msg}\033[0m" }
end
# yellow
def warning(*messages)
puts messages.map { |msg| "\033[1;33m#{msg}\033[0m" }
end
# green
def success(*messages)
puts messages.map { |msg| "\033[1;32m#{msg}\033[0m" }
end
alias_method :message, :success
# magenta
def note(*messages)
puts messages.map { |msg| "\033[1;35m#{msg}\033[0m" }
end
# blue
def info(*messages)
puts messages.map { |msg| "\033[1;34m#{msg}\033[0m" }
end
end
module ThorUI
extend ColorfulMessages
end

1
spec/integration/rails/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
vendor/plugins/webrat

View File

@ -0,0 +1,10 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'

View File

@ -0,0 +1,15 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => 'ceaca978d06f1c9db5c84193c1447572'
# See ActionController::Base for details
# Uncomment this to filter the contents of submitted sensitive data parameters
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
end

View File

@ -0,0 +1,14 @@
class WebratController < ApplicationController
def form
end
def submit
render :text => "OK"
end
def redirect
redirect_to :submit
end
end

View File

@ -0,0 +1,17 @@
<h1>Webrat Form</h1>
<% form_tag submit_path do %>
<label>
Text field <%= text_field_tag "text_field" %>
</label>
<label>
TOS <%= check_box_tag "tos" %>
</label>
<label>
<%= select_tag "month", "<option></option><option>January</option>" %>
</label>
<%= submit_tag "Test" %>
<% end %>

View File

@ -0,0 +1,109 @@
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion rescue nil
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
require 'rubygems'
min_version = '1.3.1'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!

View File

@ -0,0 +1,75 @@
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use. To use Rails without a database
# you must remove the Active Record framework.
config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
# You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3)
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time.
config.time_zone = 'UTC'
# The internationalization framework can be changed to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_rails_app_session',
:secret => '81f33872c27349e86f1dc2cd6708995b9c26578e6e2d8992e567cd64d96e844343149f6e2f44bf178304141db9ce39e741e0e60699867c29c51c6d7ef7dc9556'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# Please note that observers generated using script/generate observer need to have an _observer suffix
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
end

View File

@ -0,0 +1,17 @@
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false

View File

@ -0,0 +1,22 @@
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test

View File

@ -0,0 +1,10 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end

View File

@ -0,0 +1,5 @@
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

View File

@ -0,0 +1,17 @@
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
if defined?(ActiveRecord)
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
# Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
end
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false

View File

@ -0,0 +1,5 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"

View File

@ -0,0 +1,8 @@
ActionController::Routing::Routes.draw do |map|
map.with_options :controller => "webrat" do |webrat|
webrat.submit "/submit", :action => "submit"
webrat.redirect "/redirect", :action => "redirect"
webrat.root :action => "form"
end
end

View File

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>

View File

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The change you wanted was rejected (422)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/422.html -->
<div class="dialog">
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
</html>

View File

@ -0,0 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>We're sorry, but something went wrong (500)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
<p>We've been notified about this issue and we'll take a look at it shortly.</p>
<p><small>(If you're the administrator of this website, then please read
the log file "<%=h RAILS_ENV %>.log"
to find out what went wrong.)</small></p>
</div>
</body>
</html>

View File

@ -0,0 +1,4 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
$LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info"
require 'commands/about'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/console'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/dbconsole'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/destroy'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/generate'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/benchmarker'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/profiler'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/performance/request'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/plugin'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/process/inspector'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/process/reaper'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/process/spawner'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/runner'

View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server'

View File

@ -0,0 +1,22 @@
require 'test_helper'
class WebratTest < ActionController::IntegrationTest
test "should visit pages" do
visit root_path
assert_tag "Webrat Form"
assert response.body.include?("Webrat Form")
end
test "should submit forms" do
visit root_path
fill_in "Text field", :with => "Hello"
check "TOS"
select "January"
click_button "Test"
end
test "should follow redirects" do
visit redirect_path
assert response.body.include?("OK")
end
end

View File

@ -0,0 +1,21 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require "redgreen"
require File.dirname(__FILE__) + "/../../../../lib/webrat"
Webrat.configure do |config|
config.mode = :rails
end
ActionController::Base.class_eval do
def perform_action
perform_action_without_rescue
end
end
Dispatcher.class_eval do
def self.failsafe_response(output, status, exception = nil)
raise exception
end
end

View File

@ -25,6 +25,16 @@ describe Webrat::Configuration do
config.should open_error_files config.should open_error_files
end end
it "should use 'selenium' as the selenium environment by default" do
config = Webrat::Configuration.new
config.selenium_environment.should == :selenium
end
it "should use 3001 as the selenium port by default" do
config = Webrat::Configuration.new
config.selenium_port.should == 3001
end
it "should be configurable with a block" do it "should be configurable with a block" do
Webrat.configure do |config| Webrat.configure do |config|
config.open_error_files = false config.open_error_files = false

View File

@ -1,47 +1,47 @@
require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper") require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe Webrat::Session do describe Webrat::Session do
it "should not have a doc_root" do it "should not have a doc_root" do
session = Webrat::Session.new session = Webrat::Session.new
session.doc_root.should be_nil session.doc_root.should be_nil
end end
it "should expose the current_dom" do it "should expose the current_dom" do
session = Webrat::Session.new session = Webrat::Session.new
def session.response def session.response
Object.new Object.new
end end
def session.response_body def session.response_body
"<html></html>" "<html></html>"
end end
session.should respond_to(:current_dom) session.should respond_to(:current_dom)
end end
it "should open the page in the browser in MacOSX" do it "should open the page in the browser in MacOSX" do
session = Webrat::Session.new session = Webrat::Session.new
session.stub!(:ruby_platform => 'darwin') session.stub!(:ruby_platform => 'darwin')
session.should_receive(:`).with("open path") session.should_receive(:`).with("open path")
session.open_in_browser("path") session.open_in_browser("path")
end end
it "should open the page in the browser in cygwin" do it "should open the page in the browser in cygwin" do
session = Webrat::Session.new session = Webrat::Session.new
session.stub!(:ruby_platform => 'i386-cygwin') session.stub!(:ruby_platform => 'i386-cygwin')
session.should_receive(:`).with("rundll32 url.dll,FileProtocolHandler path\\to\\file") session.should_receive(:`).with("rundll32 url.dll,FileProtocolHandler path\\to\\file")
session.open_in_browser("path/to/file") session.open_in_browser("path/to/file")
end end
it "should open the page in the browser in Win32" do it "should open the page in the browser in Win32" do
session = Webrat::Session.new session = Webrat::Session.new
session.stub!(:ruby_platform => 'win32') session.stub!(:ruby_platform => 'win32')
session.should_receive(:`).with("rundll32 url.dll,FileProtocolHandler path\\to\\file") session.should_receive(:`).with("rundll32 url.dll,FileProtocolHandler path\\to\\file")
session.open_in_browser("path/to/file") session.open_in_browser("path/to/file")
end end
it "should provide a current_page for backwards compatibility" do it "should provide a current_page for backwards compatibility" do
session = Webrat::Session.new session = Webrat::Session.new
current_page = session.current_page current_page = session.current_page
@ -58,7 +58,7 @@ describe Webrat::Session do
it "should return a copy of the headers to be sent" do it "should return a copy of the headers to be sent" do
session = Webrat::Session.new session = Webrat::Session.new
session.instance_eval { session.instance_eval {
@default_headers = {'HTTP_X_FORWARDED_FOR' => '192.168.1.1'} @default_headers = {'HTTP_X_FORWARDED_FOR' => '192.168.1.1'}
@custom_headers = {'Accept' => 'application/xml'} @custom_headers = {'Accept' => 'application/xml'}
} }
@ -89,17 +89,17 @@ describe Webrat::Session do
before(:each) do before(:each) do
webrat_session = Webrat::Session.new webrat_session = Webrat::Session.new
end end
it "should raise an error if the request is not a success" do it "should raise an error if the request is not a success" do
webrat_session.stub!(:get) webrat_session.stub!(:get)
webrat_session.stub!(:response_body => "Exception caught") webrat_session.stub!(:response_body => "Exception caught")
webrat_session.stub!(:response_code => 500) webrat_session.stub!(:response_code => 500)
webrat_session.stub!(:formatted_error => "application error") webrat_session.stub!(:formatted_error => "application error")
webrat_session.stub!(:save_and_open_page) webrat_session.stub!(:save_and_open_page)
lambda { webrat_session.request_page('some url', :get, {}) }.should raise_error(Webrat::PageLoadError) lambda { webrat_session.request_page('some url', :get, {}) }.should raise_error(Webrat::PageLoadError)
end end
it "should raise an error but not open if the request is not a success and config quashes save_and_open" do it "should raise an error but not open if the request is not a success and config quashes save_and_open" do
Webrat.configure do |config| Webrat.configure do |config|
config.open_error_files = false config.open_error_files = false
@ -109,8 +109,33 @@ describe Webrat::Session do
webrat_session.stub!(:response_code => 500) webrat_session.stub!(:response_code => 500)
webrat_session.stub!(:formatted_error => "application error") webrat_session.stub!(:formatted_error => "application error")
webrat_session.should_not_receive(:save_and_open_page) webrat_session.should_not_receive(:save_and_open_page)
lambda { webrat_session.request_page('some url', :get, {}) }.should raise_error(Webrat::PageLoadError) lambda { webrat_session.request_page('some url', :get, {}) }.should raise_error(Webrat::PageLoadError)
end end
it "should follow redirects" do
webrat_session.should_receive(:redirect?).twice.and_return(true, false)
webrat_session.response.should_receive(:headers).once.and_return({ "Location" => "/newurl" })
webrat_session.request_page("/oldurl", :get, {})
webrat_session.current_url.should == "/newurl"
end
end end
end
describe "#redirect?" do
before(:each) do
webrat_session = Webrat::Session.new
end
it "should return true if the last response was a redirect" do
webrat_session.stub!(:response_code => 301)
webrat_session.redirect?.should be_true
end
it "should return false if the last response wasn't a redirect" do
webrat_session.stub!(:response_code => 200)
webrat_session.redirect?.should be_false
end
end
end

View File

@ -0,0 +1,81 @@
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
require "webrat/mechanize"
describe Webrat::MechanizeSession do
before :each do
Webrat.configuration.mode = :mechanize
end
before(:each) do
@mech = Webrat::MechanizeSession.new
end
describe "headers method" do
it "should return empty headers for a newly initialized session" do
@mech.headers.should == {}
end
end
describe "post" do
def url
'http://test.host/users'
end
def data
{:user => {:first_name => 'Nancy', :last_name => 'Callahan'}}
end
def flattened_data
{'user[first_name]' => 'Nancy', 'user[last_name]' => 'Callahan'}
end
it "should flatten model post data" do
mechanize = mock(:mechanize)
WWW::Mechanize.stub!(:new => mechanize)
mechanize.should_receive(:post).with(url, flattened_data)
Webrat::MechanizeSession.new.post(url, data)
end
end
describe "#absolute_url" do
before(:each) do
@session = Webrat::MechanizeSession.new
@session.stub!(:current_url).and_return(absolute_url)
end
def absolute_url
'http://test.host/users/fred/cabbages'
end
def rooted_url
'/users/fred/cabbages'
end
def relative_url
'../../wilma'
end
it "should return unmodified url if prefixed with scheme" do
@session.absolute_url(absolute_url).should == absolute_url
end
it "should prefix scheme and hostname if url begins with /" do
@session.absolute_url(rooted_url).should == absolute_url
end
it "should resolve sibling URLs relative to current path" do
@session.absolute_url(relative_url).should == 'http://test.host/users/wilma'
end
it "should cope with sibling URLs from root of site" do
@session.stub!(:current_url).and_return('http://test.host')
@session.absolute_url(relative_url).should == 'http://test.host/wilma'
end
it "should cope with https" do
@session.stub!(:current_url).and_return('https://test.host')
@session.absolute_url(relative_url).should == 'https://test.host/wilma'
end
end
end

View File

@ -0,0 +1,42 @@
require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
require "webrat/merb"
describe Webrat::MerbSession do
it "should not pass empty params if data is and empty hash" do
session = Webrat::MerbSession.new
response = OpenStruct.new
response.status = 200
session.should_receive(:request).with('url', {:params=> nil, :method=>"GET", :headers=>nil}).and_return(response)
session.get('url', {}, nil)
end
%w{post put delete}.each do |request_method|
it "should call do request with method #{request_method.upcase} for a #{request_method} call" do
session = Webrat::MerbSession.new
response = OpenStruct.new
response.status = 200
session.should_receive(:request).with('url', {:params=>nil, :method=>request_method.upcase, :headers=>nil}).and_return(response)
session.send(request_method, 'url', {}, nil)
end
end
context "a session with a response" do
setup do
@session = Webrat::MerbSession.new
@response = OpenStruct.new
@response.status = 200
@response.body = 'test response'
@session.instance_variable_set(:@response, @response)
end
it "should return body of a request as a response_body" do
@session.response_body.should == @response.body
end
it "should return status of a request as a response_code" do
@session.response_code.should == @response.status
end
end
end

View File

@ -0,0 +1,88 @@
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
require "webrat/rails"
describe Webrat::RailsSession do
before :each do
Webrat.configuration.mode = :rails
@integration_session = mock("integration_session")
end
it "should delegate response_body to the session response body" do
@integration_session.stub!(:response => mock("response", :body => "<html>"))
Webrat::RailsSession.new(@integration_session).response_body.should == "<html>"
end
it "should delegate response_code to the session response code" do
@integration_session.stub!(:response => mock("response", :code => "42"))
Webrat::RailsSession.new(@integration_session).response_code.should == 42
end
it "should delegate get to the integration session" do
@integration_session.should_receive(:get).with("url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.get("url", "data", "headers")
end
it "should delegate post to the integration session" do
@integration_session.should_receive(:post).with("url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.post("url", "data", "headers")
end
it "should delegate put to the integration session" do
@integration_session.should_receive(:put).with("url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.put("url", "data", "headers")
end
it "should delegate delete to the integration session" do
@integration_session.should_receive(:delete).with("url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.delete("url", "data", "headers")
end
context "the URL is a full path" do
it "should just pass on the path" do
@integration_session.stub!(:https!)
@integration_session.should_receive(:get).with("/url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.get("http://www.example.com/url", "data", "headers")
end
end
context "the URL is https://" do
it "should call #https! with true before the request and just pass on the path" do
@integration_session.should_receive(:https!).with(true)
@integration_session.should_receive(:get).with("/url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.get("https://www.example.com/url", "data", "headers")
end
end
context "the URL is http://" do
it "should call #https! with true before the request" do
@integration_session.stub!(:get)
@integration_session.should_receive(:https!).with(false)
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.get("http://www.example.com/url", "data", "headers")
end
end
context "the URL include an anchor" do
it "should strip out the anchor" do
@integration_session.should_receive(:https!).with(false)
@integration_session.should_receive(:get).with("/url", "data", "headers")
rails_session = Webrat::RailsSession.new(@integration_session)
rails_session.get("http://www.example.com/url#foo", "data", "headers")
end
end
it "should provide a saved_page_dir" do
Webrat::RailsSession.new(mock("integration session")).should respond_to(:saved_page_dir)
end
it "should provide a doc_root" do
Webrat::RailsSession.new(mock("integration session")).should respond_to(:doc_root)
end
end

View File

@ -0,0 +1,15 @@
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
require "webrat/sinatra"
class Sinatra::Application
# Override this to prevent Sinatra from barfing on the options passed from RSpec
def self.load_default_options_from_command_line!
end
end
Sinatra::Application.default_options.merge!(
:env => :test,
:run => false,
:raise_errors => true,
:logging => false
)

View File

@ -0,0 +1,28 @@
require File.expand_path(File.dirname(__FILE__) + '/helper')
describe Webrat::SinatraSession do
before :each do
Webrat.configuration.mode = :sinatra
@sinatra_session = Webrat::SinatraSession.new
end
it "should delegate get to get_it" do
@sinatra_session.should_receive(:get_it).with("url", { :env => "headers" })
@sinatra_session.get("url", {}, "headers")
end
it "should delegate post to post_it" do
@sinatra_session.should_receive(:post_it).with("url", { :env => "headers" })
@sinatra_session.post("url", {}, "headers")
end
it "should delegate put to put_it" do
@sinatra_session.should_receive(:put_it).with("url", { :env => "headers" })
@sinatra_session.put("url", {}, "headers")
end
it "should delegate delete to delete_it" do
@sinatra_session.should_receive(:delete_it).with("url", { :env => "headers" })
@sinatra_session.delete("url", {}, "headers")
end
end

View File

@ -24,7 +24,7 @@ describe "click_area" do
webrat_session.response_code = 501 webrat_session.response_code = 501
lambda { click_area "Berlin" }.should raise_error(Webrat::PageLoadError) lambda { click_area "Berlin" }.should raise_error(Webrat::PageLoadError)
end end
[200, 300, 400, 499].each do |status| [200, 300, 400, 499].each do |status|
it "should consider the #{status} status code as success" do it "should consider the #{status} status code as success" do
with_html <<-HTML with_html <<-HTML
@ -34,11 +34,12 @@ describe "click_area" do
</map> </map>
</html> </html>
HTML HTML
webrat_session.stub!(:redirect? => false)
webrat_session.response_code = status webrat_session.response_code = status
lambda { click_area "Berlin" }.should_not raise_error lambda { click_area "Berlin" }.should_not raise_error
end end
end end
it "should fail if the area doesn't exist" do it "should fail if the area doesn't exist" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -47,12 +48,12 @@ describe "click_area" do
</map> </map>
</html> </html>
HTML HTML
lambda { lambda {
click_area "Missing area" click_area "Missing area"
}.should raise_error(Webrat::NotFoundError) }.should raise_error(Webrat::NotFoundError)
end end
it "should not be case sensitive" do it "should not be case sensitive" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -64,7 +65,7 @@ describe "click_area" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_area "berlin" click_area "berlin"
end end
it "should follow relative links" do it "should follow relative links" do
webrat_session.stub!(:current_url => "/page") webrat_session.stub!(:current_url => "/page")
@ -78,7 +79,7 @@ describe "click_area" do
webrat_session.should_receive(:get).with("/page/sub", {}) webrat_session.should_receive(:get).with("/page/sub", {})
click_area "Berlin" click_area "Berlin"
end end
it "should follow fully qualified local links" do it "should follow fully qualified local links" do
with_html <<-HTML with_html <<-HTML
<html> <html>

View File

@ -7,10 +7,10 @@ describe "click_button" do
<form method="get" action="/login"></form> <form method="get" action="/login"></form>
</html> </html>
HTML HTML
lambda { click_button }.should raise_error(Webrat::NotFoundError) lambda { click_button }.should raise_error(Webrat::NotFoundError)
end end
it "should fail if input is not a submit button" do it "should fail if input is not a submit button" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -23,7 +23,7 @@ describe "click_button" do
lambda { click_button }.should raise_error(Webrat::NotFoundError) lambda { click_button }.should raise_error(Webrat::NotFoundError)
end end
it "should fail if button is disabled" do it "should fail if button is disabled" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -35,7 +35,7 @@ describe "click_button" do
lambda { click_button }.should raise_error(Webrat::DisabledFieldError) lambda { click_button }.should raise_error(Webrat::DisabledFieldError)
end end
it "should default to get method" do it "should default to get method" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -47,7 +47,7 @@ describe "click_button" do
webrat_session.should_receive(:get) webrat_session.should_receive(:get)
click_button click_button
end end
it "should assert valid response" do it "should assert valid response" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -59,7 +59,7 @@ describe "click_button" do
webrat_session.response_code = 501 webrat_session.response_code = 501
lambda { click_button }.should raise_error(Webrat::PageLoadError) lambda { click_button }.should raise_error(Webrat::PageLoadError)
end end
[200, 300, 400, 499].each do |status| [200, 300, 400, 499].each do |status|
it "should consider the #{status} status code as success" do it "should consider the #{status} status code as success" do
with_html <<-HTML with_html <<-HTML
@ -69,11 +69,12 @@ describe "click_button" do
</form> </form>
</html> </html>
HTML HTML
webrat_session.stub!(:redirect? => false)
webrat_session.response_code = status webrat_session.response_code = status
lambda { click_button }.should_not raise_error lambda { click_button }.should_not raise_error
end end
end end
it "should submit the first form by default" do it "should submit the first form by default" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -88,7 +89,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/form1", {}) webrat_session.should_receive(:get).with("/form1", {})
click_button click_button
end end
it "should not explode on file fields" do it "should not explode on file fields" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -100,7 +101,7 @@ describe "click_button" do
HTML HTML
click_button click_button
end end
it "should submit the form with the specified button" do it "should submit the form with the specified button" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -115,7 +116,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/form2", {}) webrat_session.should_receive(:get).with("/form2", {})
click_button "Form2" click_button "Form2"
end end
it "should use action from form" do it "should use action from form" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -127,7 +128,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", {}) webrat_session.should_receive(:get).with("/login", {})
click_button click_button
end end
it "should use method from form" do it "should use method from form" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -139,7 +140,7 @@ describe "click_button" do
webrat_session.should_receive(:post) webrat_session.should_receive(:post)
click_button click_button
end end
it "should send button as param if it has a name" do it "should send button as param if it has a name" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -152,7 +153,7 @@ describe "click_button" do
webrat_session.should_receive(:post).with("/login", "login" => "Login") webrat_session.should_receive(:post).with("/login", "login" => "Login")
click_button("Login") click_button("Login")
end end
it "should not send button as param if it has no name" do it "should not send button as param if it has no name" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -177,8 +178,8 @@ describe "click_button" do
HTML HTML
webrat_session.should_receive(:get).with("/login", "user" => {"password" => "mypass"}) webrat_session.should_receive(:get).with("/login", "user" => {"password" => "mypass"})
click_button click_button
end end
it "should send default hidden field values" do it "should send default hidden field values" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -191,7 +192,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"email" => "test@example.com"}) webrat_session.should_receive(:get).with("/login", "user" => {"email" => "test@example.com"})
click_button click_button
end end
it "should send default text field values" do it "should send default text field values" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -204,7 +205,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"email" => "test@example.com"}) webrat_session.should_receive(:get).with("/login", "user" => {"email" => "test@example.com"})
click_button click_button
end end
it "should not send disabled field values" do it "should not send disabled field values" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -221,7 +222,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", {}) webrat_session.should_receive(:get).with("/login", {})
click_button click_button
end end
it "should send default checked fields" do it "should send default checked fields" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -234,7 +235,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"tos" => "1"}) webrat_session.should_receive(:get).with("/login", "user" => {"tos" => "1"})
click_button click_button
end end
it "should send default radio options" do it "should send default radio options" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -250,7 +251,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"gender" => "F"}) webrat_session.should_receive(:get).with("/login", "user" => {"gender" => "F"})
click_button click_button
end end
it "should send correct data for rails style unchecked fields" do it "should send correct data for rails style unchecked fields" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -264,7 +265,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"tos" => "0"}) webrat_session.should_receive(:get).with("/login", "user" => {"tos" => "0"})
click_button click_button
end end
it "should send correct data for rails style checked fields" do it "should send correct data for rails style checked fields" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -302,7 +303,7 @@ describe "click_button" do
"response" => { "choices" => [{"selected" => "one"}, {"selected" => "two"}, {"selected" => "two"}]}) "response" => { "choices" => [{"selected" => "one"}, {"selected" => "two"}, {"selected" => "two"}]})
click_button click_button
end end
it "should not send default unchecked fields" do it "should not send default unchecked fields" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -315,7 +316,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", {}) webrat_session.should_receive(:get).with("/login", {})
click_button click_button
end end
it "should send default textarea values" do it "should send default textarea values" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -328,7 +329,7 @@ describe "click_button" do
webrat_session.should_receive(:post).with("/posts", "post" => {"body" => "Post body here!"}) webrat_session.should_receive(:post).with("/posts", "post" => {"body" => "Post body here!"})
click_button click_button
end end
it "should properly handle HTML entities in textarea default values" do it "should properly handle HTML entities in textarea default values" do
spec = lambda do spec = lambda do
with_html <<-HTML with_html <<-HTML
@ -342,14 +343,14 @@ describe "click_button" do
webrat_session.should_receive(:post).with("/posts", "post" => {"body" => "Peanut butter & jelly"}) webrat_session.should_receive(:post).with("/posts", "post" => {"body" => "Peanut butter & jelly"})
click_button click_button
end end
if Webrat.on_java? if Webrat.on_java?
spec.call spec.call
else else
pending("needs bug fix", &spec) pending("needs bug fix", &spec)
end end
end end
it "should send default selected option value from select" do it "should send default selected option value from select" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -381,7 +382,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "month" => "February") webrat_session.should_receive(:get).with("/login", "month" => "February")
click_button click_button
end end
it "should send first select option value when no option selected" do it "should send first select option value when no option selected" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -397,7 +398,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "month" => "1") webrat_session.should_receive(:get).with("/login", "month" => "1")
click_button click_button
end end
it "should handle nested properties" do it "should handle nested properties" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -449,7 +450,7 @@ describe "click_button" do
webrat_session.should_receive(:get) webrat_session.should_receive(:get)
click_button click_button
end end
it "should find buttons by their IDs" do it "should find buttons by their IDs" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -461,7 +462,7 @@ describe "click_button" do
webrat_session.should_receive(:get) webrat_session.should_receive(:get)
click_button "my_button" click_button "my_button"
end end
it "should find image buttons by their alt text" do it "should find image buttons by their alt text" do
with_html <<-HTML with_html <<-HTML
<html> <html>

View File

@ -10,7 +10,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "Save & go back" click_link "Save & go back"
end end
it "should use get by default" do it "should use get by default" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -30,7 +30,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "Link text", :method => :get click_link "Link text", :method => :get
end end
it "should click link on substring" do it "should click link on substring" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -40,7 +40,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "ink tex", :method => :get click_link "ink tex", :method => :get
end end
it "should click delete links" do it "should click delete links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -50,8 +50,8 @@ describe "click_link" do
webrat_session.should_receive(:delete).with("/page", {}) webrat_session.should_receive(:delete).with("/page", {})
click_link "Link text", :method => :delete click_link "Link text", :method => :delete
end end
it "should click post links" do it "should click post links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -61,7 +61,7 @@ describe "click_link" do
webrat_session.should_receive(:post).with("/page", {}) webrat_session.should_receive(:post).with("/page", {})
click_link "Link text", :method => :post click_link "Link text", :method => :post
end end
it "should click put links" do it "should click put links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -71,7 +71,7 @@ describe "click_link" do
webrat_session.should_receive(:put).with("/page", {}) webrat_session.should_receive(:put).with("/page", {})
click_link "Link text", :method => :put click_link "Link text", :method => :put
end end
it "should click links by regexp" do it "should click links by regexp" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -81,8 +81,8 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link /link [a-z]/i click_link /link [a-z]/i
end end
it "should click links by id" do it "should click links by id" do
with_html <<-HTML with_html <<-HTML
<html> <html>
<a id="link_text_link" href="/page">Link text</a> <a id="link_text_link" href="/page">Link text</a>
@ -91,8 +91,8 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "link_text_link" click_link "link_text_link"
end end
it "should click links by id regexp" do it "should click links by id regexp" do
with_html <<-HTML with_html <<-HTML
<html> <html>
<a id="link_text_link" href="/page">Link text</a> <a id="link_text_link" href="/page">Link text</a>
@ -101,7 +101,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link /_text_/ click_link /_text_/
end end
it "should click rails javascript links with authenticity tokens" do it "should click rails javascript links with authenticity tokens" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -122,7 +122,7 @@ describe "click_link" do
webrat_session.should_receive(:post).with("/posts", "authenticity_token" => "aa79cb354597a60a3786e7e291ed4f74d77d3a62") webrat_session.should_receive(:post).with("/posts", "authenticity_token" => "aa79cb354597a60a3786e7e291ed4f74d77d3a62")
click_link "Posts" click_link "Posts"
end end
it "should click rails javascript delete links" do it "should click rails javascript delete links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -143,7 +143,7 @@ describe "click_link" do
webrat_session.should_receive(:delete).with("/posts/1", {}) webrat_session.should_receive(:delete).with("/posts/1", {})
click_link "Delete" click_link "Delete"
end end
it "should click rails javascript post links" do it "should click rails javascript post links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -159,7 +159,7 @@ describe "click_link" do
webrat_session.should_receive(:post).with("/posts", {}) webrat_session.should_receive(:post).with("/posts", {})
click_link "Posts" click_link "Posts"
end end
it "should click rails javascript post links without javascript" do it "should click rails javascript post links without javascript" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -175,7 +175,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/posts", {}) webrat_session.should_receive(:get).with("/posts", {})
click_link "Posts", :javascript => false click_link "Posts", :javascript => false
end end
it "should click rails javascript put links" do it "should click rails javascript put links" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -196,7 +196,7 @@ describe "click_link" do
webrat_session.should_receive(:put).with("/posts", {}) webrat_session.should_receive(:put).with("/posts", {})
click_link "Put" click_link "Put"
end end
it "should fail if the javascript link doesn't have a value for the _method input" do it "should fail if the javascript link doesn't have a value for the _method input" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -213,12 +213,12 @@ describe "click_link" do
return false;">Link</a> return false;">Link</a>
</html> </html>
HTML HTML
lambda { lambda {
click_link "Link" click_link "Link"
}.should raise_error(Webrat::WebratError) }.should raise_error(Webrat::WebratError)
end end
it "should assert valid response" do it "should assert valid response" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -228,7 +228,7 @@ describe "click_link" do
webrat_session.response_code = 501 webrat_session.response_code = 501
lambda { click_link "Link text" }.should raise_error(Webrat::PageLoadError) lambda { click_link "Link text" }.should raise_error(Webrat::PageLoadError)
end end
[200, 300, 400, 499].each do |status| [200, 300, 400, 499].each do |status|
it "should consider the #{status} status code as success" do it "should consider the #{status} status code as success" do
with_html <<-HTML with_html <<-HTML
@ -236,23 +236,24 @@ describe "click_link" do
<a href="/page">Link text</a> <a href="/page">Link text</a>
</html> </html>
HTML HTML
webrat_session.stub!(:redirect? => false)
webrat_session.response_code = status webrat_session.response_code = status
lambda { click_link "Link text" }.should_not raise_error lambda { click_link "Link text" }.should_not raise_error
end end
end end
it "should fail is the link doesn't exist" do it "should fail is the link doesn't exist" do
with_html <<-HTML with_html <<-HTML
<html> <html>
<a href="/page">Link text</a> <a href="/page">Link text</a>
</html> </html>
HTML HTML
lambda { lambda {
click_link "Missing link" click_link "Missing link"
}.should raise_error(Webrat::NotFoundError) }.should raise_error(Webrat::NotFoundError)
end end
it "should not be case sensitive" do it "should not be case sensitive" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -262,7 +263,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "LINK TEXT" click_link "LINK TEXT"
end end
it "should match link substrings" do it "should match link substrings" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -272,7 +273,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "Link text" click_link "Link text"
end end
it "should work with elements in the link" do it "should work with elements in the link" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -282,7 +283,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page", {}) webrat_session.should_receive(:get).with("/page", {})
click_link "Link text" click_link "Link text"
end end
it "should match the first matching link" do it "should match the first matching link" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -293,7 +294,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page1", {}) webrat_session.should_receive(:get).with("/page1", {})
click_link "Link text" click_link "Link text"
end end
it "should choose the shortest link text match" do it "should choose the shortest link text match" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -301,22 +302,22 @@ describe "click_link" do
<a href="/page2">Link</a> <a href="/page2">Link</a>
</html> </html>
HTML HTML
webrat_session.should_receive(:get).with("/page2", {}) webrat_session.should_receive(:get).with("/page2", {})
click_link "Link" click_link "Link"
end end
it "should treat non-breaking spaces as spaces" do it "should treat non-breaking spaces as spaces" do
with_html <<-HTML with_html <<-HTML
<html> <html>
<a href="/page1">This&nbsp;is&nbsp;a&nbsp;link</a> <a href="/page1">This&nbsp;is&nbsp;a&nbsp;link</a>
</html> </html>
HTML HTML
webrat_session.should_receive(:get).with("/page1", {}) webrat_session.should_receive(:get).with("/page1", {})
click_link "This is a link" click_link "This is a link"
end end
it "should not match on non-text contents" do it "should not match on non-text contents" do
pending "needs fix" do pending "needs fix" do
with_html <<-HTML with_html <<-HTML
@ -325,12 +326,12 @@ describe "click_link" do
<a href="/page2">Location</a> <a href="/page2">Location</a>
</html> </html>
HTML HTML
webrat_session.should_receive(:get).with("/page2", {}) webrat_session.should_receive(:get).with("/page2", {})
click_link "Location" click_link "Location"
end end
end end
it "should click link within a selector" do it "should click link within a selector" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -340,7 +341,7 @@ describe "click_link" do
</div> </div>
</html> </html>
HTML HTML
webrat_session.should_receive(:get).with("/page2", {}) webrat_session.should_receive(:get).with("/page2", {})
click_link_within "#container", "Link" click_link_within "#container", "Link"
end end
@ -366,7 +367,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page/sub", {}) webrat_session.should_receive(:get).with("/page/sub", {})
click_link "Jump to sub page" click_link "Jump to sub page"
end end
it "should follow fully qualified local links" do it "should follow fully qualified local links" do
webrat_session.stub!(:current_url => "/page") webrat_session.stub!(:current_url => "/page")
with_html <<-HTML with_html <<-HTML
@ -377,7 +378,7 @@ describe "click_link" do
webrat_session.should_receive(:get).with("http://subdomain.example.com/page/sub", {}) webrat_session.should_receive(:get).with("http://subdomain.example.com/page/sub", {})
click_link "Jump to sub page" click_link "Jump to sub page"
end end
it "should follow fully qualified local links to example.com" do it "should follow fully qualified local links to example.com" do
with_html <<-HTML with_html <<-HTML
<html> <html>
@ -398,28 +399,28 @@ describe "click_link" do
webrat_session.should_receive(:get).with("/page?foo=bar", {}) webrat_session.should_receive(:get).with("/page?foo=bar", {})
click_link "Jump to foo bar" click_link "Jump to foo bar"
end end
it "should matches_text? on regexp" do it "should matches_text? on regexp" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
link.should_receive(:text).and_return(@link_text_with_nbsp) link.should_receive(:text).and_return(@link_text_with_nbsp)
link.matches_text?(/link/i).should == 0 link.matches_text?(/link/i).should == 0
end end
it "should matches_text? on link_text" do it "should matches_text? on link_text" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
link.should_receive(:text).and_return(@link_text_with_nbsp) link.should_receive(:text).and_return(@link_text_with_nbsp)
link.matches_text?("Link Text").should == 0 link.matches_text?("Link Text").should == 0
end end
it "should matches_text? on substring" do it "should matches_text? on substring" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
link.should_receive(:text).and_return(@link_text_with_nbsp) link.should_receive(:text).and_return(@link_text_with_nbsp)
link.matches_text?("nk Te").should_not be_nil link.matches_text?("nk Te").should_not be_nil
end end
it "should not matches_text? on link_text case insensitive" do it "should not matches_text? on link_text case insensitive" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
@ -428,15 +429,15 @@ describe "click_link" do
link.should_receive(:title).and_return(nil) link.should_receive(:title).and_return(nil)
link.matches_text?("link_text").should == false link.matches_text?("link_text").should == false
end end
it "should match text not include &nbsp;" do it "should match text not include &nbsp;" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
link.should_receive(:text).and_return('LinkText') link.should_receive(:text).and_return('LinkText')
link.matches_text?("LinkText").should == 0 link.matches_text?("LinkText").should == 0
end end
it "should not matches_text? on wrong text" do it "should not matches_text? on wrong text" do
pending "need to update these" pending "need to update these"
link = Webrat::Link.new(webrat_session, nil) link = Webrat::Link.new(webrat_session, nil)
nbsp = [0xA0].pack("U") nbsp = [0xA0].pack("U")
@ -464,5 +465,5 @@ describe "click_link" do
link.should_receive(:inner_html).and_return('<img src="logo.png" />') link.should_receive(:inner_html).and_return('<img src="logo.png" />')
link.matches_text?('logo.png').should == 10 link.matches_text?('logo.png').should == 10
end end
end end

View File

@ -13,22 +13,32 @@ describe "visit" do
webrat_session.should_receive(:get).with("/", {}) webrat_session.should_receive(:get).with("/", {})
visit("/") visit("/")
end end
it "should assert valid response" do it "should assert valid response" do
webrat_session.response_code = 501 webrat_session.response_code = 501
lambda { visit("/") }.should raise_error(Webrat::PageLoadError) lambda { visit("/") }.should raise_error(Webrat::PageLoadError)
end end
[200, 300, 400, 499].each do |status| [200, 300, 400, 499].each do |status|
it "should consider the #{status} status code as success" do it "should consider the #{status} status code as success" do
webrat_session.stub!(:redirect? => false)
webrat_session.response_code = status webrat_session.response_code = status
lambda { visit("/") }.should_not raise_error lambda { visit("/") }.should_not raise_error
end end
end end
it "should require a visit before manipulating page" do it "should require a visit before manipulating page" do
lambda { fill_in "foo", :with => "blah" }.should raise_error(Webrat::WebratError) lambda { fill_in "foo", :with => "blah" }.should raise_error(Webrat::WebratError)
end end
it "should follow redirects" do
webrat_session.should_receive(:redirect?).twice.and_return(true, false)
webrat_session.response.should_receive(:headers).once.and_return({ "Location" => "/newurl" })
visit("/oldurl")
current_url.should == "/newurl"
end
end end
describe "visit with referer" do describe "visit with referer" do
@ -45,5 +55,5 @@ describe "visit with referer" do
webrat_session.should_receive(:get).with("/", {}, {"HTTP_REFERER" => "/old_url"}) webrat_session.should_receive(:get).with("/", {}, {"HTTP_REFERER" => "/old_url"})
visit("/") visit("/")
end end
end end

Some files were not shown because too many files have changed in this diff Show More