More work on OOP implementation

This commit is contained in:
Bryan Helmkamp 2008-04-07 05:52:49 +01:00
parent 857b46fe3e
commit f38ed15704
25 changed files with 667 additions and 354 deletions

View File

@ -27,7 +27,7 @@ module ActionController
@current_page = Webrat::Page.new(self, *args) @current_page = Webrat::Page.new(self, *args)
end end
[:fills_in, :clicks_button, :selects, :chooses, :checks, :unchecks].each do |method_name| [:reloads, :fills_in, :clicks_button, :selects, :chooses, :checks, :unchecks, :clicks_link, :clicks_put_link, :clicks_get_link, :clicks_post_link, :clicks_delete_link].each do |method_name|
define_method(method_name) do |*args| define_method(method_name) do |*args|
current_page.send(method_name, *args) current_page.send(method_name, *args)
end end
@ -37,5 +37,3 @@ module ActionController
end end
end end

View File

@ -0,0 +1,25 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class ButtonField < Field
def matches_value?(value)
@element["value"] =~ /^\W*#{value}\b/i
end
def to_param
return nil if @value.nil?
super
end
def default_value
nil
end
def click
set(@element["value"]) unless @element["name"].blank?
@form.submit
end
end
end

View File

@ -1,30 +0,0 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field_finder"))
module Webrat
class ButtonFinder < FieldFinder
def initialize(root, name = nil)
@root = root
@id_or_name_or_label = name
@element_types = %w[input]
@input_types = %w[submit image]
@candidates = nil
end
def find
if @id_or_name_or_label.nil?
candidates.first
else
find_by_id(@id_or_name_or_label) ||
find_by_name ||
find_by_value
end
end
protected
def find_by_value
candidates.detect { |el| el.attributes["value"] == @id_or_name_or_label }
end
end
end

View File

@ -0,0 +1,30 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class CheckboxField < Field
def to_param
return nil if @value.nil?
super
end
def check
set(@element["value"] || "on")
end
def uncheck
set(nil)
end
protected
def default_value
if @element["checked"] == "checked"
@element["value"] || "on"
else
nil
end
end
end
end

200
lib/webrat/field.rb Normal file
View File

@ -0,0 +1,200 @@
module Webrat
class Field
def self.class_for_element(element)
case element.name
when "select"
SelectField
when "textarea"
TextareaField
when "input"
case element["type"]
when "checkbox"
CheckboxField
when "radio"
RadioField
when "text"
TextField
when "hidden"
HiddenField
when "password"
PasswordField
when "reset"
ResetField
when "submit"
ButtonField
when "image"
ButtonField
else
raise "Invalid field element: #{element.inspect}"
end
else
raise "Invalid field element: #{element.inspect}"
end
end
def initialize(form, element)
@form = form
@element = element
@value = default_value
end
def label_text
return nil unless label
label.text
end
def matches_id?(id)
@element["id"] == id.to_s
end
def matches_name?(name)
@element["name"] == name.to_s
end
def matches_label?(label_text)
return false unless label
label.matches_text?(label_text)
end
def to_param
param_parser.parse_query_parameters("#{name}=#{@value}")
end
def set(value)
@value = value
end
def unset
@value = default_value
end
protected
def id
@element["id"]
end
def name
@element["name"]
end
def label
return nil if label_element.nil?
@label ||= Label.new(self, label_element)
end
def label_element
@label_element ||= begin
parent = @element.parent
while parent.respond_to?(:parent)
return parent if parent.name == "label"
parent = parent.parent
end
if id.blank?
nil
else
@form.element.at("label[@for=#{id}]")
end
end
end
def default_value
@element["value"]
end
def param_parser
if defined?(CGIMethods)
CGIMethods
else
ActionController::AbstractRequest
end
end
end
end
# module Webrat
# class FieldFinder
# def initialize(root, id_or_name_or_label, element_types, input_types = nil)
# @root = root
# @id_or_name_or_label = id_or_name_or_label.to_s
# @element_types = Array(element_types)
# @input_types = Array(input_types)
#
# @candidates = nil
# end
#
# def find
# find_by_id(@id_or_name_or_label) ||
# find_by_name ||
# find_by_label
# end
#
# protected
#
# # def find_select_list_by_name_or_label(name_or_label) # :nodoc:
# # select = find_element_by_name("select", name_or_label)
# # return select if select
# #
# # label = find_form_label(name_or_label)
# # label ? field_for_label(label) : nil
# # end
# #
# # def find_option_by_value(option_value, select=nil) # :nodoc:
# # options = select.nil? ? (dom / "option") : (select / "option")
# # options.detect { |el| el.innerHTML == option_value }
# # end
#
# def field_for_label(label)
# inputs_within_label = canidates_within(label)
#
# if inputs_within_label.any?
# inputs_within_label.first
# else
# find_by_id(label["for"])
# end
# end
#
# def find_by_id(id)
# candidates.detect { |el| el["id"] == id }
# end
#
# def find_by_name
# candidates.detect { |el| el["name"] == @id_or_name_or_label }
# end
#
# def find_by_label
# label = canididate_labels.sort_by { |el| el.innerText.strip.size }.first
# label ? field_for_label(label) : nil
# end
#
# def canididate_labels
# (@root / "label").select { |el| el.innerText =~ /^\W*#{Regexp.escape(@id_or_name_or_label)}\b/i }
# end
#
# def candidates
# return @candidates if @candidates
# @candidates = canidates_within(@root)
# end
#
# def canidates_within(root)
# candidates = []
#
# @element_types.each do |element_type|
# if "input" == element_type && @input_types.any?
# @input_types.each do |input_type|
# candidates += (root / "input[@type=#{input_type}]")
# end
# else
# candidates += (root / element_type)
# end
# end
#
# candidates
# end
#
# end
# end

View File

@ -1,82 +0,0 @@
module Webrat
class FieldFinder
def initialize(root, id_or_name_or_label, element_types, input_types = nil)
@root = root
@id_or_name_or_label = id_or_name_or_label.to_s
@element_types = Array(element_types)
@input_types = Array(input_types)
@candidates = nil
end
def find
find_by_id(@id_or_name_or_label) ||
find_by_name ||
find_by_label
end
protected
# def find_select_list_by_name_or_label(name_or_label) # :nodoc:
# select = find_element_by_name("select", name_or_label)
# return select if select
#
# label = find_form_label(name_or_label)
# label ? field_for_label(label) : nil
# end
#
# def find_option_by_value(option_value, select=nil) # :nodoc:
# options = select.nil? ? (dom / "option") : (select / "option")
# options.detect { |el| el.innerHTML == option_value }
# end
def field_for_label(label)
inputs_within_label = canidates_within(label)
if inputs_within_label.any?
inputs_within_label.first
else
find_by_id(label.attributes["for"])
end
end
def find_by_id(id)
candidates.detect { |el| el.attributes["id"] == id }
end
def find_by_name
candidates.detect { |el| el.attributes["name"] == @id_or_name_or_label }
end
def find_by_label
label = canididate_labels.sort_by { |el| el.innerText.strip.size }.first
label ? field_for_label(label) : nil
end
def canididate_labels
(@root / "label").select { |el| el.innerText =~ /^\W*#{Regexp.escape(@id_or_name_or_label)}\b/i }
end
def candidates
return @candidates if @candidates
@candidates = canidates_within(@root)
end
def canidates_within(root)
candidates = []
@element_types.each do |element_type|
if "input" == element_type && @input_types.any?
@input_types.each do |input_type|
candidates += (root / "input[@type=#{input_type}]")
end
else
candidates += (root / element_type)
end
end
candidates
end
end
end

View File

@ -1,110 +1,110 @@
module Webrat module Webrat
class Form class Form
def initialize(page, form) attr_reader :element
def initialize(page, element)
@page = page @page = page
@form = form @element = element
@params = default_params @fields = nil
end end
def set(input_element, value) def find_field(id_or_name_or_label, *field_types)
new_param = param_parser.parse_query_parameters("#{input_element.attributes["name"]}=#{value}") possible_fields = fields_by_type(field_types)
merge(new_param)
find_field_by_id(possible_fields, id_or_name_or_label) ||
find_field_by_name(possible_fields, id_or_name_or_label) ||
find_field_by_label(possible_fields, id_or_name_or_label) ||
nil
end end
def unset(input_element) def find_button(value = nil)
@params.delete(input_element.attributes['name']) return fields_by_type([ButtonField]).first if value.nil?
possible_buttons = fields_by_type([ButtonField])
possible_buttons.each do |possible_button|
return possible_button if possible_button.matches_value?(value)
end end
def find_field(*args) nil
FieldFinder.new(@form, *args).find
end
def find_button(name = nil)
ButtonFinder.new(@form, name).find
end end
def submit def submit
Page.new(@page.session, form_action, form_method, @params) Page.new(@page.session, form_action, form_method, params)
end end
protected protected
# def find_field_by_name(name) # :nodoc: def find_field_by_id(possible_fields, id)
# find_element_by_name("input", name) || find_element_by_name("textarea", name) possible_fields.each do |possible_field|
# end return possible_field if possible_field.matches_id?(id)
#
# def add_default_params_for(form) # :nodoc:
# add_default_params_from_inputs_for(form)
# add_default_params_from_checkboxes_for(form)
# add_default_params_from_radio_buttons_for(form)
# add_default_params_from_textareas_for(form)
# add_default_params_from_selects_for(form)
# end
def default_params
{}
end end
def add_default_params_from_radio_buttons_for(form) # :nodoc: nil
(form / "input[@type='radio][@checked='checked']").each do |input|
add_form_data(input, input.attributes["value"])
end
end end
def add_default_params_from_checkboxes_for(form) # :nodoc: def find_field_by_name(possible_fields, name)
(form / "input[@type='checkbox][@checked='checked']").each do |input| possible_fields.each do |possible_field|
add_form_data(input, input.attributes["value"] || "on") return possible_field if possible_field.matches_name?(name)
end
end end
def add_default_params_from_selects_for(form) # :nodoc: nil
(form / "select").each do |select|
selected_options = select / "option[@selected='selected']"
selected_options = select / "option:first" if selected_options.empty?
selected_options.each do |option|
add_form_data(select, option.attributes["value"] || option.innerHTML)
end
end
end end
def add_default_params_from_inputs_for(form) # :nodoc: def find_field_by_label(possible_fields, label)
(form / "input").each do |input| matching_fields = []
next unless %w[text password hidden].include?(input.attributes["type"])
add_form_data(input, input.attributes["value"]) possible_fields.each do |possible_field|
end matching_fields << possible_field if possible_field.matches_label?(label)
end end
def add_default_params_from_textareas_for(form) # :nodoc: matching_fields.sort_by { |f| f.label_text.length }.first
(form / "textarea").each do |input|
add_form_data(input, input.inner_html)
end end
def fields_by_type(field_types)
fields.select { |f| field_types.include?(f.class) }
end
def fields
return @fields if @fields
@fields = []
(@element / "input, textarea, select").each do |field_element|
@fields << Field.class_for_element(field_element).new(self, field_element)
end
@fields
end
def params
all_params = {}
fields.each do |field|
next if field.to_param.nil?
merge(all_params, field.to_param)
end
all_params
end end
def form_method def form_method
@form.attributes["method"].blank? ? :get : @form.attributes["method"].downcase @element["method"].blank? ? :get : @element["method"].downcase
end end
def form_action def form_action
@form.attributes["action"].blank? ? current_url : @form.attributes["action"] @element["action"].blank? ? @page.url : @element["action"]
end end
def param_parser def merge(all_params, new_param)
if defined?(CGIMethods)
CGIMethods
else
ActionController::AbstractRequest
end
end
def merge(new_param)
new_param.each do |key, value| new_param.each do |key, value|
case @params[key] case all_params[key]
when Hash, HashWithIndifferentAccess when Hash, HashWithIndifferentAccess
merge_hash_values(@params[key], value) merge_hash_values(all_params[key], value)
when Array when Array
@params[key] += value all_params[key] += value
else else
@params[key] = value all_params[key] = value
end end
end end
end end

View File

@ -0,0 +1,27 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class HiddenField < Field
def to_param
if collection_name?
super
else
checkbox_with_same_name = @form.find_field(name, CheckboxField)
if checkbox_with_same_name.to_param.nil?
super
else
nil
end
end
end
protected
def collection_name?
name =~ /\[\]/
end
end
end

18
lib/webrat/label.rb Normal file
View File

@ -0,0 +1,18 @@
module Webrat
class Label
def initialize(field, element)
@field = field
@element = element
end
def matches_text?(label_text)
text =~ /^\W*#{Regexp.escape(label_text.to_s)}\b/i
end
def text
@element.innerText
end
end
end

View File

@ -1,14 +1,32 @@
module Webrat module Webrat
class Link class Link
def initialize(link_element) def initialize(page, element)
@page = page
@element = element
end end
def click def click(method = nil)
method ||= http_method
return if href =~ /^#/ && method == :get
Page.new(@page.session, href, method, authenticity_token.blank? ? {} : {"authenticity_token" => authenticity_token})
end
def matches_text?(link_text)
text =~ /#{Regexp.escape(link_text.to_s)}/i
end
def text
@element.innerHTML
end end
protected protected
def href
@element["href"]
end
def authenticity_token def authenticity_token
return unless onclick && onclick.include?("s.setAttribute('name', 'authenticity_token');") && return unless onclick && onclick.include?("s.setAttribute('name', 'authenticity_token');") &&
onclick =~ /s\.setAttribute\('value', '([a-f0-9]{40})'\);/ onclick =~ /s\.setAttribute\('value', '([a-f0-9]{40})'\);/
@ -16,28 +34,26 @@ module Webrat
end end
def onclick def onclick
@element["onclick"]
end end
def http_method def http_method
end
def http_method_from_js(onclick)
if !onclick.blank? && onclick.include?("f.submit()") if !onclick.blank? && onclick.include?("f.submit()")
http_method_from_js_form(onclick) http_method_from_js_form
else else
:get :get
end end
end end
def http_method_from_js_form(onclick) def http_method_from_js_form
if onclick.include?("m.setAttribute('name', '_method')") if onclick.include?("m.setAttribute('name', '_method')")
http_method_from_fake_method_param(onclick) http_method_from_fake_method_param
else else
:post :post
end end
end end
def http_method_from_fake_method_param(onclick) def http_method_from_fake_method_param
if onclick.include?("m.setAttribute('value', 'delete')") if onclick.include?("m.setAttribute('value', 'delete')")
:delete :delete
elsif onclick.include?("m.setAttribute('value', 'put')") elsif onclick.include?("m.setAttribute('value', 'put')")
@ -49,3 +65,28 @@ module Webrat
end end
end end
# def clicks_link_with_method(link_text, http_method) # :nodoc:
# link = all_links.detect { |el| el.innerHTML =~ /#{link_text}/i }
# flunk("No link with text #{link_text.inspect} was found") if link.nil?
# request_page(http_method, link["href"])
# end
#
# def find_shortest_matching_link(links, link_text)
# candidates = links.select { |el| el.innerHTML =~ /#{link_text}/i }
# candidates.sort_by { |el| el.innerText.strip.size }.first
# end
#
# def clicks_one_link_of(links, link_text)
# link = find_shortest_matching_link(links, link_text)
#
# flunk("No link with text #{link_text.inspect} was found") if link.nil?
#
# onclick = link["onclick"]
# href = link["href"]
#
# http_method = http_method_from_js(onclick)
# authenticity_token = authenticity_token_value(onclick)
#
# request_page(http_method, href, authenticity_token.blank? ? {} : {"authenticity_token" => authenticity_token})
# end

View File

@ -1,32 +0,0 @@
# def clicks_link_with_method(link_text, http_method) # :nodoc:
# link = all_links.detect { |el| el.innerHTML =~ /#{link_text}/i }
# flunk("No link with text #{link_text.inspect} was found") if link.nil?
# request_page(http_method, link.attributes["href"])
# end
#
# def find_shortest_matching_link(links, link_text)
# candidates = links.select { |el| el.innerHTML =~ /#{link_text}/i }
# candidates.sort_by { |el| el.innerText.strip.size }.first
# end
#
# def clicks_one_link_of(links, link_text)
# link = find_shortest_matching_link(links, link_text)
#
# flunk("No link with text #{link_text.inspect} was found") if link.nil?
#
# onclick = link.attributes["onclick"]
# href = link.attributes["href"]
#
# http_method = http_method_from_js(onclick)
# authenticity_token = authenticity_token_value(onclick)
#
# request_page(http_method, href, authenticity_token.blank? ? {} : {"authenticity_token" => authenticity_token}) unless href =~ /^#/ && http_method == :get
# end
#
# def all_links # :nodoc:
# (dom / "a[@href]")
# end
#
# def links_within(selector) # :nodoc:
# (dom / selector / "a[@href]")
# end

View File

@ -6,6 +6,7 @@ module Webrat
include Logging include Logging
attr_reader :session attr_reader :session
attr_reader :url
def initialize(session, url = nil, method = :get, data = {}) def initialize(session, url = nil, method = :get, data = {})
@session = session @session = session
@ -27,25 +28,10 @@ module Webrat
# The field value is required, and must be specified in <tt>options[:with]</tt>. # The field value is required, and must be specified in <tt>options[:with]</tt>.
# <tt>field</tt> can be either the value of a name attribute (i.e. <tt>user[email]</tt>) # <tt>field</tt> can be either the value of a name attribute (i.e. <tt>user[email]</tt>)
# or the text inside a <tt><label></tt> element that points at the <tt><input></tt> field. # or the text inside a <tt><label></tt> element that points at the <tt><input></tt> field.
def fills_in(field, options = {}) def fills_in(id_or_name_or_label, options = {})
value = options[:with] field = find_field(id_or_name_or_label, TextField, TextareaField)
flunk("No value was provided") if value.nil? flunk("Could not find text or password input or textarea #{id_or_name_or_label.inspect}") if field.nil?
field.set(options[:with])
form_with_input = nil
found_input = nil
forms.each do |form|
found_input = form.find_field(field, %w[input textarea], %w[text password])
if found_input
form_with_input = form
break
end
end
flunk("Could not find input #{field.inspect}") if found_input.nil?
form_with_input.set(found_input, value)
end end
# Verifies that an input checkbox exists on the current page and marks it # Verifies that an input checkbox exists on the current page and marks it
@ -53,11 +39,10 @@ module Webrat
# #
# Example: # Example:
# checks 'Remember Me' # checks 'Remember Me'
def checks(field) def checks(id_or_name_or_label)
checkbox = find_field_by_name_or_label(field) field = find_field(id_or_name_or_label, CheckboxField)
flunk("Could not find checkbox #{field.inspect}") if checkbox.nil? flunk("Could not find checkbox #{id_or_name_or_label.inspect}") if field.nil?
flunk("Input #{checkbox.inspect} is not a checkbox") unless checkbox.attributes['type'] == 'checkbox' field.check
add_form_data(checkbox, checkbox.attributes["value"] || "on")
end end
# Verifies that an input checkbox exists on the current page and marks it # Verifies that an input checkbox exists on the current page and marks it
@ -65,16 +50,10 @@ module Webrat
# #
# Example: # Example:
# unchecks 'Remember Me' # unchecks 'Remember Me'
def unchecks(field) def unchecks(id_or_name_or_label)
checkbox = find_field_by_name_or_label(field) field = find_field(id_or_name_or_label, CheckboxField)
flunk("Could not find checkbox #{field.inspect}") if checkbox.nil? flunk("Could not find checkbox #{id_or_name_or_label.inspect}") if field.nil?
flunk("Input #{checkbox.inspect} is not a checkbox") unless checkbox.attributes['type'] == 'checkbox' field.uncheck
remove_form_data(checkbox)
(form_for_node(checkbox) / "input").each do |input|
next unless input.attributes["type"] == "hidden" && input.attributes["name"] == checkbox.attributes["name"]
add_form_data(input, input.attributes["value"])
end
end end
# Verifies that an input radio button exists on the current page and marks it # Verifies that an input radio button exists on the current page and marks it
@ -85,8 +64,8 @@ module Webrat
def chooses(field) def chooses(field)
radio = find_field_by_name_or_label(field) radio = find_field_by_name_or_label(field)
flunk("Could not find radio button #{field.inspect}") if radio.nil? flunk("Could not find radio button #{field.inspect}") if radio.nil?
flunk("Input #{radio.inspect} is not a radio button") unless radio.attributes['type'] == 'radio' flunk("Input #{radio.inspect} is not a radio button") unless radio['type'] == 'radio'
add_form_data(radio, radio.attributes["value"] || "on") add_form_data(radio, radio["value"] || "on")
end end
# Verifies that a an option element exists on the current page with the specified # Verifies that a an option element exists on the current page with the specified
@ -99,18 +78,12 @@ module Webrat
# selects "February", :from => "event_month" # selects "February", :from => "event_month"
# selects "February", :from => "Event Month" # selects "February", :from => "Event Month"
def selects(option_text, options = {}) def selects(option_text, options = {})
if options[:from] id_or_name_or_label = options[:from]
select = find_select_list_by_name_or_label(options[:from]) field = find_field(id_or_name_or_label, SelectField)
flunk("Could not find select list #{options[:from].inspect}") if select.nil? flunk("Could not find select #{id_or_name_or_label.inspect}") if field.nil?
option_node = find_option_by_value(option_text, select) option = field.find_option(option_text)
flunk("Could not find option #{option_text.inspect}") if option_node.nil? flunk("Could not find option #{option_text.inspect}") if option.nil?
else option.choose
option_node = find_option_by_value(option_text)
flunk("Could not find option #{option_text.inspect}") if option_node.nil?
select = option_node.parent
end
add_form_data(select, option_node.attributes["value"] || option_node.innerHTML)
# TODO - Set current form
end end
# Saves the currently loaded page out to RAILS_ROOT/tmp/ and opens it in the default # Saves the currently loaded page out to RAILS_ROOT/tmp/ and opens it in the default
@ -138,23 +111,25 @@ module Webrat
# Example: # Example:
# clicks_link "Sign up" # clicks_link "Sign up"
def clicks_link(link_text) def clicks_link(link_text)
clicks_one_link_of(all_links, link_text) link = find_link(link_text)
link.click
end end
# Works like clicks_link, but only looks for the link text within a given selector # # Works like clicks_link, but only looks for the link text within a given selector
# # #
# Example: # # Example:
# clicks_link_within "#user_12", "Vote" # # clicks_link_within "#user_12", "Vote"
def clicks_link_within(selector, link_text) # def clicks_link_within(selector, link_text)
clicks_one_link_of(links_within(selector), link_text) # clicks_one_link_of(links_within(selector), link_text)
end # end
# Works like clicks_link, but forces a GET request # Works like clicks_link, but forces a GET request
# #
# Example: # Example:
# clicks_get_link "Log out" # clicks_get_link "Log out"
def clicks_get_link(link_text) def clicks_get_link(link_text)
clicks_link_with_method(link_text, :get) link = find_link(link_text)
link.click(:get)
end end
# Works like clicks_link, but issues a DELETE request instead of a GET # Works like clicks_link, but issues a DELETE request instead of a GET
@ -162,7 +137,8 @@ module Webrat
# Example: # Example:
# clicks_delete_link "Log out" # clicks_delete_link "Log out"
def clicks_delete_link(link_text) def clicks_delete_link(link_text)
clicks_link_with_method(link_text, :delete) link = find_link(link_text)
link.click(:delete)
end end
# Works like clicks_link, but issues a POST request instead of a GET # Works like clicks_link, but issues a POST request instead of a GET
@ -170,7 +146,8 @@ module Webrat
# Example: # Example:
# clicks_post_link "Vote" # clicks_post_link "Vote"
def clicks_post_link(link_text) def clicks_post_link(link_text)
clicks_link_with_method(link_text, :post) link = find_link(link_text)
link.click(:post)
end end
# Works like clicks_link, but issues a PUT request instead of a GET # Works like clicks_link, but issues a PUT request instead of a GET
@ -178,7 +155,8 @@ module Webrat
# Example: # Example:
# clicks_put_link "Update profile" # clicks_put_link "Update profile"
def clicks_put_link(link_text) def clicks_put_link(link_text)
clicks_link_with_method(link_text, :put) link = find_link(link_text)
link.click(:put)
end end
# Verifies that a submit button exists for the form, then submits the form, follows # Verifies that a submit button exists for the form, then submits the form, follows
@ -191,21 +169,15 @@ module Webrat
# The URL and HTTP method for the form submission are automatically read from the # The URL and HTTP method for the form submission are automatically read from the
# <tt>action</tt> and <tt>method</tt> attributes of the <tt><form></tt> element. # <tt>action</tt> and <tt>method</tt> attributes of the <tt><form></tt> element.
def clicks_button(value = nil) def clicks_button(value = nil)
form_with_button = nil button = nil
found_button = nil
forms.each do |form| forms.each do |form|
found_button = form.find_button(value) button = form.find_button(value)
break if button
if found_button
form_with_button = form
break
end
end end
flunk("Could not find button #{value.inspect}") if found_button.nil? flunk("Could not find button #{value.inspect}") if button.nil?
form_with_button.set(found_button, found_button.attributes["value"]) unless found_button.attributes["name"].blank? button.click
form_with_button.submit
end end
# Reloads the last page requested. Note that this will resubmit forms # Reloads the last page requested. Note that this will resubmit forms
@ -222,6 +194,30 @@ module Webrat
protected protected
def find_link(text)
matching_links = []
links.each do |possible_link|
matching_links << possible_link if possible_link.matches_text?(text)
end
if matching_links.any?
matching_links.sort_by { |l| l.text.length }.first
else
flunk("Could not find link with text #{text.inspect}")
end
end
def find_field(id_or_name_or_label, *field_types)
forms.each do |form|
result = form.find_field(id_or_name_or_label, *field_types)
return result if result
end
nil
end
def request_page(url, method, data) def request_page(url, method, data)
debug_log "REQUESTING PAGE: #{method.to_s.upcase} #{url} with #{data.inspect}" debug_log "REQUESTING PAGE: #{method.to_s.upcase} #{url} with #{data.inspect}"
@ -241,23 +237,18 @@ module Webrat
def reset_dom def reset_dom
@dom = nil @dom = nil
@links = nil
@forms = nil @forms = nil
end end
def find_button(value = nil) # :nodoc: def links
return nil unless value return @links if @links
(dom / "input[@type='submit']").detect do |el| @links = (dom / "a[@href]").map do |link_element|
el.attributes["value"] =~ /^\W*#{value}\b/i Link.new(self, link_element)
end end
end end
def form_for_node(node) # :nodoc:
return node if node.name == "form"
node = node.parent until node.name == "form"
node
end
def forms def forms
return @forms if @forms return @forms if @forms

View File

@ -0,0 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class PasswordField < Field
end
end

17
lib/webrat/radio_field.rb Normal file
View File

@ -0,0 +1,17 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class RadioField < Field
protected
def default_value
if @element["checked"] == "checked"
@element["value"]
else
nil
end
end
end
end

View File

@ -0,0 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class ResetField < Field
end
end

View File

@ -0,0 +1,29 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class SelectField < Field
def find_option(text)
options.detect { |o| o.matches_text?(text) }
end
protected
def default_value
selected_options = @element / "option[@selected='selected']"
selected_options = @element / "option:first" if selected_options.empty?
selected_options.map do |option|
option["value"] || option.innerHTML
end
end
def options
option_elements.map { |oe| SelectOption.new(self, oe) }
end
def option_elements
(@element / "option")
end
end
end

View File

@ -0,0 +1,25 @@
module Webrat
class SelectOption
def initialize(select, element)
@select = select
@element = element
end
def matches_text?(text)
# require "rubygems"; require "ruby-debug"; Debugger.start; debugger
@element.innerHTML =~ /^\W*#{Regexp.escape(text.to_s)}\b/i
end
def choose
@select.set(value)
end
protected
def value
@element["value"] || @element.innerHTML
end
end
end

6
lib/webrat/text_field.rb Normal file
View File

@ -0,0 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class TextField < Field
end
end

View File

@ -0,0 +1,13 @@
require File.expand_path(File.join(File.dirname(__FILE__), "field"))
module Webrat
class TextareaField < Field
protected
def default_value
@element.inner_html
end
end
end

View File

@ -13,9 +13,11 @@ class ChecksTest < Test::Unit::TestCase
<form method="post" action="/login"> <form method="post" action="/login">
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.checks "remember_me" @session.checks "remember_me"
end end
end
def test_should_fail_if_input_is_not_a_checkbox def test_should_fail_if_input_is_not_a_checkbox
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -23,9 +25,11 @@ class ChecksTest < Test::Unit::TestCase
<input type="text" name="remember_me" /> <input type="text" name="remember_me" />
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.checks "remember_me" @session.checks "remember_me"
end end
end
def test_should_check_rails_style_checkboxes def test_should_check_rails_style_checkboxes
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -79,9 +83,11 @@ class UnchecksTest < Test::Unit::TestCase
<form method="post" action="/login"> <form method="post" action="/login">
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.unchecks "remember_me" @session.unchecks "remember_me"
end end
end
def test_should_fail_if_input_is_not_a_checkbox def test_should_fail_if_input_is_not_a_checkbox
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -89,9 +95,11 @@ class UnchecksTest < Test::Unit::TestCase
<input type="text" name="remember_me" /> <input type="text" name="remember_me" />
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.unchecks "remember_me" @session.unchecks "remember_me"
end end
end
def test_should_uncheck_rails_style_checkboxes def test_should_uncheck_rails_style_checkboxes
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -103,6 +111,7 @@ class UnchecksTest < Test::Unit::TestCase
</form> </form>
EOS EOS
@session.expects(:get_via_redirect).with("/login", "user" => {"tos" => "0"}) @session.expects(:get_via_redirect).with("/login", "user" => {"tos" => "0"})
@session.checks "TOS"
@session.unchecks "TOS" @session.unchecks "TOS"
@session.clicks_button @session.clicks_button
end end

View File

@ -14,9 +14,11 @@ class ChoosesTest < Test::Unit::TestCase
<form method="post" action="/login"> <form method="post" action="/login">
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.chooses "first option" @session.chooses "first option"
end end
end
def test_should_fail_if_input_is_not_a_radio_button def test_should_fail_if_input_is_not_a_radio_button
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -24,9 +26,11 @@ class ChoosesTest < Test::Unit::TestCase
<input type="text" name="first_option" /> <input type="text" name="first_option" />
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.chooses "first_option" @session.chooses "first_option"
end end
end
def test_should_check_rails_style_radio_buttons def test_should_check_rails_style_radio_buttons
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)

View File

@ -5,6 +5,8 @@ class ClicksButtonTest < Test::Unit::TestCase
@session = ActionController::Integration::Session.new @session = ActionController::Integration::Session.new
@session.stubs(:assert_response) @session.stubs(:assert_response)
@session.stubs(:get_via_redirect) @session.stubs(:get_via_redirect)
@page = Webrat::Page.new(@session)
@session.stubs(:current_page).returns(@page)
@response = mock @response = mock
@session.stubs(:response).returns(@response) @session.stubs(:response).returns(@response)
end end
@ -13,9 +15,11 @@ class ClicksButtonTest < Test::Unit::TestCase
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
<form method="get" action="/login"></form> <form method="get" action="/login"></form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.clicks_button @session.clicks_button
end end
end
def test_should_fail_if_input_is_not_a_submit_button def test_should_fail_if_input_is_not_a_submit_button
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -23,9 +27,11 @@ class ClicksButtonTest < Test::Unit::TestCase
<input type="reset" /> <input type="reset" />
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.clicks_button @session.clicks_button
end end
end
def test_should_default_to_get_method def test_should_default_to_get_method
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -53,7 +59,7 @@ class ClicksButtonTest < Test::Unit::TestCase
<input type="submit" /> <input type="submit" />
</form> </form>
EOS EOS
@session.expects(:current_url).returns("/current") @page.stubs(:url).returns("/current")
@session.expects(:get_via_redirect).with("/current", {}) @session.expects(:get_via_redirect).with("/current", {})
@session.clicks_button @session.clicks_button
end end
@ -225,7 +231,7 @@ class ClicksButtonTest < Test::Unit::TestCase
</form> </form>
EOS EOS
@session.expects(:post_via_redirect).with("/login", @session.expects(:post_via_redirect).with("/login",
"options" => ["soda", "soda", "dessert", "burger", "fries"], "options" => ["burger", "fries", "soda", "soda", "dessert"],
"response" => { "choices" => [{"selected" => "one"}, {"selected" => "two"}, {"selected" => "two"}]}) "response" => { "choices" => [{"selected" => "one"}, {"selected" => "two"}, {"selected" => "two"}]})
@session.clicks_button @session.clicks_button
end end

View File

@ -170,17 +170,17 @@ class ClicksLinkTest < Test::Unit::TestCase
@session.clicks_link "Link" @session.clicks_link "Link"
end end
def test_should_click_link_within_a_selector # def test_should_click_link_within_a_selector
@response.stubs(:body).returns(<<-EOS) # @response.stubs(:body).returns(<<-EOS)
<a href="/page1">Link</a> # <a href="/page1">Link</a>
<div id="container"> # <div id="container">
<a href="/page2">Link</a> # <a href="/page2">Link</a>
</div> # </div>
EOS # EOS
#
@session.expects(:get_via_redirect).with("/page2", {}) # @session.expects(:get_via_redirect).with("/page2", {})
@session.clicks_link_within "#container", "Link" # @session.clicks_link_within "#container", "Link"
end # end
def test_should_not_make_request_when_link_is_local_anchor def test_should_not_make_request_when_link_is_local_anchor
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)

View File

@ -45,7 +45,7 @@ class FillsInTest < Test::Unit::TestCase
@session.clicks_button @session.clicks_button
end end
def test_should_choose_the_closest_label_match def test_should_choose_the_shortest_label_match
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
<form method="post" action="/login"> <form method="post" action="/login">
<label for="user_mail1">Some other mail</label> <label for="user_mail1">Some other mail</label>

View File

@ -14,8 +14,10 @@ class SelectsTest < Test::Unit::TestCase
<select name="month"><option value="1">January</option></select> <select name="month"><option value="1">January</option></select>
</form> </form>
EOS EOS
@session.expects(:flunk)
@session.selects "February" assert_raises RuntimeError do
@session.selects "February", :from => "month"
end
end end
def test_should_fail_if_option_not_found_in_list_specified_by_element_name def test_should_fail_if_option_not_found_in_list_specified_by_element_name
@ -25,9 +27,11 @@ class SelectsTest < Test::Unit::TestCase
<select name="year"><option value="2008">2008</option></select> <select name="year"><option value="2008">2008</option></select>
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.selects "February", :from => "year" @session.selects "February", :from => "year"
end end
end
def test_should_fail_if_specified_list_not_found def test_should_fail_if_specified_list_not_found
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -35,9 +39,11 @@ class SelectsTest < Test::Unit::TestCase
<select name="month"><option value="1">January</option></select> <select name="month"><option value="1">January</option></select>
</form> </form>
EOS EOS
@session.expects(:flunk)
assert_raises RuntimeError do
@session.selects "February", :from => "year" @session.selects "February", :from => "year"
end end
end
def test_should_send_value_from_option def test_should_send_value_from_option
@response.stubs(:body).returns(<<-EOS) @response.stubs(:body).returns(<<-EOS)
@ -47,7 +53,7 @@ class SelectsTest < Test::Unit::TestCase
</form> </form>
EOS EOS
@session.expects(:post_via_redirect).with("/login", "month" => "1") @session.expects(:post_via_redirect).with("/login", "month" => "1")
@session.selects "January" @session.selects "January", :from => "month"
@session.clicks_button @session.clicks_button
end end
@ -87,7 +93,7 @@ class SelectsTest < Test::Unit::TestCase
</form> </form>
EOS EOS
@session.expects(:post_via_redirect).with("/login", "month" => "January") @session.expects(:post_via_redirect).with("/login", "month" => "January")
@session.selects "January" @session.selects "January", :from => "month"
@session.clicks_button @session.clicks_button
end end
end end