Whitespace

This commit is contained in:
Bryan Helmkamp 2009-04-07 20:30:12 -04:00
parent f3f81dabdc
commit 03914fd293
107 changed files with 824 additions and 824 deletions

View File

@ -11,7 +11,7 @@ module Webrat
def self.require_xml
gem "nokogiri", ">= 1.0.6"
if on_java?
# We need Nokogiri's CSS to XPath support, even if using REXML and Hpricot for parsing and searching
require "nokogiri/css"
@ -22,11 +22,11 @@ module Webrat
require "webrat/core/xml/nokogiri"
end
end
def self.on_java?
RUBY_PLATFORM =~ /java/
end
end
Webrat.require_xml

View File

@ -57,7 +57,7 @@ module Webrat
# How many redirects to the same URL should be halted as an infinite redirect
# loop? Defaults to 10
attr_accessor :infinite_redirect_limit
def initialize # :nodoc:
self.open_error_files = true
self.parse_with_nokogiri = !Webrat.on_java?
@ -82,7 +82,7 @@ module Webrat
# :rails, :selenium, :rack, :sinatra, :mechanize, :merb
def mode=(mode)
@mode = mode.to_sym
# This is a temporary hack to support backwards compatibility
# with Merb 1.0.8 until it's updated to use the new Webrat.configure
# syntax

View File

@ -2,21 +2,21 @@ require "webrat/core/elements/element"
module Webrat
class Area < Element #:nodoc:
def self.xpath_search
".//area"
end
def click(method = nil, options = {})
@session.request_page(absolute_href, :get, {})
end
protected
def href
Webrat::XML.attribute(@element, "href")
end
def absolute_href
if href =~ /^\?/
"#{@session.current_url}#{href}"
@ -26,6 +26,6 @@ module Webrat
href
end
end
end
end
end

View File

@ -1,33 +1,33 @@
module Webrat
class Element # :nodoc:
def self.load_all(session, dom)
Webrat::XML.xpath_search(dom, xpath_search).map do |element|
Webrat::XML.xpath_search(dom, xpath_search).map do |element|
load(session, element)
end
end
def self.load(session, element)
return nil if element.nil?
session.elements[Webrat::XML.xpath_to(element)] ||= self.new(session, element)
end
attr_reader :element
def initialize(session, element)
@session = session
@element = element
end
def path
Webrat::XML.xpath_to(@element)
end
def inspect
"#<#{self.class} @element=#{element.inspect}>"
end
end
end
end

View File

@ -8,10 +8,10 @@ module Webrat
# Raised when Webrat is asked to manipulate a disabled form field
class DisabledFieldError < WebratError
end
class Field < Element #:nodoc:
attr_reader :value
def self.xpath_search
[".//button", ".//input", ".//textarea", ".//select"]
end
@ -19,22 +19,22 @@ module Webrat
def self.xpath_search_excluding_hidden
[".//button", ".//input[ @type != 'hidden']", ".//textarea", ".//select"]
end
def self.field_classes
@field_classes || []
end
def self.inherited(klass)
@field_classes ||= []
@field_classes << klass
# raise args.inspect
end
def self.load(session, element)
return nil if element.nil?
session.elements[Webrat::XML.xpath_to(element)] ||= field_class(element).new(session, element)
end
def self.field_class(element)
case element.name
when "button" then ButtonField
@ -55,7 +55,7 @@ module Webrat
end
end
end
def initialize(*args)
super
@value = default_value
@ -65,7 +65,7 @@ module Webrat
return nil if labels.empty?
labels.first.text
end
def id
Webrat::XML.attribute(@element, "id")
end
@ -73,15 +73,15 @@ module Webrat
def disabled?
@element.attributes.has_key?("disabled") && Webrat::XML.attribute(@element, "disabled") != 'false'
end
def raise_error_if_disabled
return unless disabled?
raise DisabledFieldError.new("Cannot interact with disabled form element (#{self})")
end
def to_param
return nil if disabled?
case Webrat.configuration.mode
when :rails
parse_rails_request_params("#{name}=#{escaped_value}")
@ -91,17 +91,17 @@ module Webrat
{ name => escaped_value }
end
end
def set(value)
@value = value
end
def unset
@value = default_value
end
protected
def parse_rails_request_params(params)
if defined?(ActionController::AbstractRequest)
ActionController::AbstractRequest.parse_query_parameters(params)
@ -113,38 +113,38 @@ module Webrat
Rack::Utils.parse_nested_query(params)
end
end
def form
Form.load(@session, form_element)
end
def form_element
parent = @element.parent
while parent.respond_to?(:parent)
return parent if parent.name == 'form'
parent = parent.parent
end
end
def name
Webrat::XML.attribute(@element, "name")
end
def escaped_value
CGI.escape(@value.to_s)
end
def labels
@labels ||= label_elements.map do |element|
Label.load(@session, element)
end
end
def label_elements
return @label_elements unless @label_elements.nil?
@label_elements = []
parent = @element.parent
while parent.respond_to?(:parent)
if parent.name == 'label'
@ -153,18 +153,18 @@ module Webrat
end
parent = parent.parent
end
unless id.blank?
@label_elements += Webrat::XML.xpath_search(form.element, ".//label[@for = '#{id}']")
end
@label_elements
end
def default_value
Webrat::XML.attribute(@element, "value")
end
def replace_param_value(params, oval, nval)
output = Hash.new
params.each do |key, value|
@ -181,13 +181,13 @@ module Webrat
output
end
end
class ButtonField < Field #:nodoc:
def self.xpath_search
[".//button", ".//input[@type = 'submit']", ".//input[@type = 'button']", ".//input[@type = 'image']"]
end
def to_param
return nil if @value.nil?
super
@ -210,7 +210,7 @@ module Webrat
def self.xpath_search
".//input[@type = 'hidden']"
end
def to_param
if collection_name?
super
@ -238,7 +238,7 @@ module Webrat
def self.xpath_search
".//input[@type = 'checkbox']"
end
def to_param
return nil if @value.nil?
super
@ -248,7 +248,7 @@ module Webrat
raise_error_if_disabled
set(Webrat::XML.attribute(@element, "value") || "on")
end
def checked?
Webrat::XML.attribute(@element, "checked") == "checked"
end
@ -271,11 +271,11 @@ module Webrat
end
class PasswordField < Field #:nodoc:
def self.xpath_search
".//input[@type = 'password']"
end
end
class RadioField < Field #:nodoc:
@ -283,31 +283,31 @@ module Webrat
def self.xpath_search
".//input[@type = 'radio']"
end
def to_param
return nil if @value.nil?
super
end
def choose
raise_error_if_disabled
other_options.each do |option|
option.set(nil)
end
set(Webrat::XML.attribute(@element, "value") || "on")
end
def checked?
Webrat::XML.attribute(@element, "checked") == "checked"
end
protected
def other_options
form.fields.select { |f| f.name == name }
end
def default_value
if Webrat::XML.attribute(@element, "checked") == "checked"
Webrat::XML.attribute(@element, "value") || "on"
@ -323,7 +323,7 @@ module Webrat
def self.xpath_search
".//textarea"
end
protected
def default_value
@ -331,13 +331,13 @@ module Webrat
end
end
class FileField < Field #:nodoc:
def self.xpath_search
".//input[@type = 'file']"
end
attr_accessor :content_type
def set(value, content_type = nil)
@ -352,9 +352,9 @@ module Webrat
replace_param_value(super, @value, test_uploaded_file)
end
end
protected
def test_uploaded_file
if content_type
ActionController::TestUploadedFile.new(@value, content_type)
@ -386,13 +386,13 @@ module Webrat
def options
@options ||= SelectOption.load_all(@session, @element)
end
protected
def default_value
selected_options = Webrat::XML.xpath_search(@element, ".//option[@selected = 'selected']")
selected_options = Webrat::XML.xpath_search(@element, ".//option[position() = 1]") if selected_options.empty?
selected_options = Webrat::XML.xpath_search(@element, ".//option[position() = 1]") if selected_options.empty?
selected_options.map do |option|
return "" if option.nil?
Webrat::XML.attribute(option, "value") || Webrat::XML.inner_html(option)

View File

@ -7,7 +7,7 @@ require "webrat/core/locators/field_named_locator"
module Webrat
class Form < Element #:nodoc:
attr_reader :element
def self.xpath_search
".//form"
end
@ -15,21 +15,21 @@ module Webrat
def fields
@fields ||= Field.load_all(@session, @element)
end
def submit
@session.request_page(form_action, form_method, params)
end
def field_named(name, *field_types)
Webrat::Locators::FieldNamedLocator.new(@session, dom, name, *field_types).locate
end
protected
def dom
Webrat::XML.xpath_at(@session.dom, path)
end
def fields_by_type(field_types)
if field_types.any?
fields.select { |f| field_types.include?(f.class) }
@ -37,26 +37,26 @@ module Webrat
fields
end
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
def form_method
Webrat::XML.attribute(@element, "method").blank? ? :get : Webrat::XML.attribute(@element, "method").downcase
end
def form_action
Webrat::XML.attribute(@element, "action").blank? ? @session.current_url : Webrat::XML.attribute(@element, "action")
end
def merge(all_params, new_param)
new_param.each do |key, value|
case all_params[key]
@ -69,7 +69,7 @@ module Webrat
end
end
end
def merge_hash_values(a, b) # :nodoc:
a.keys.each do |k|
if b.has_key?(k)
@ -85,19 +85,19 @@ module Webrat
end
a.merge!(b)
end
def hash_classes
klasses = [Hash]
case Webrat.configuration.mode
when :rails
klasses << HashWithIndifferentAccess
when :merb
klasses << Mash
end
klasses
end
end
end

View File

@ -2,9 +2,9 @@ require "webrat/core/elements/element"
module Webrat
class Label < Element #:nodoc:
attr_reader :element
def self.xpath_search
".//label"
end
@ -12,13 +12,13 @@ module Webrat
def for_id
Webrat::XML.attribute(@element, "for")
end
def field
Field.load(@session, field_element)
end
protected
def field_element
if for_id.blank?
Webrat::XML.xpath_at(@element, *Field.xpath_search_excluding_hidden)
@ -26,6 +26,6 @@ module Webrat
Webrat::XML.css_search(@session.current_dom, "#" + for_id).first
end
end
end
end

View File

@ -4,30 +4,30 @@ require "webrat/core/elements/element"
module Webrat
class Link < Element #:nodoc:
def self.xpath_search
".//a[@href]"
end
def click(options = {})
method = options[:method] || http_method
return if href =~ /^#/ && method == :get
options[:javascript] = true if options[:javascript].nil?
if options[:javascript]
@session.request_page(absolute_href, method, data)
else
@session.request_page(absolute_href, :get, {})
end
end
protected
def id
Webrat::XML.attribute(@element, "id")
end
def data
authenticity_token.blank? ? {} : {"authenticity_token" => authenticity_token}
end
@ -49,17 +49,17 @@ module Webrat
href
end
end
def authenticity_token
return unless onclick && onclick.include?("s.setAttribute('name', 'authenticity_token');") &&
onclick =~ /s\.setAttribute\('value', '([a-f0-9]{40})'\);/
$LAST_MATCH_INFO.captures.first
end
def onclick
Webrat::XML.attribute(@element, "onclick")
end
def http_method
if !onclick.blank? && onclick.include?("f.submit()")
http_method_from_js_form
@ -87,6 +87,6 @@ module Webrat
raise Webrat::WebratError.new("No HTTP method for _method param in #{onclick.inspect}")
end
end
end
end

View File

@ -2,34 +2,34 @@ require "webrat/core/elements/element"
module Webrat
class SelectOption < Element #:nodoc:
def self.xpath_search
".//option"
end
def choose
select.raise_error_if_disabled
select.set(value)
end
protected
def select
SelectField.load(@session, select_element)
end
def select_element
parent = @element.parent
while parent.respond_to?(:parent)
return parent if parent.name == 'select'
parent = parent.parent
end
end
def value
Webrat::XML.attribute(@element, "value") || Webrat::XML.inner_html(@element)
end
end
end
end

View File

@ -11,10 +11,10 @@ require "webrat/core/locators/form_locator"
module Webrat
module Locators
def field_by_xpath(xpath)
Field.load(@session, Webrat::XML.xpath_at(dom, xpath))
end
end
end

View File

@ -2,37 +2,37 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class AreaLocator < Locator # :nodoc:
def locate
Area.load(@session, area_element)
end
def area_element
area_elements.detect do |area_element|
Webrat::XML.attribute(area_element, "title") =~ matcher ||
Webrat::XML.attribute(area_element, "id") =~ matcher
end
end
def matcher
/#{Regexp.escape(@value.to_s)}/i
end
def area_elements
Webrat::XML.xpath_search(@dom, Area.xpath_search)
end
def error_message
"Could not find area with name #{@value}"
end
end
def find_area(id_or_title) #:nodoc:
AreaLocator.new(@session, dom, id_or_title).locate!
end
end
end
end

View File

@ -2,13 +2,13 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class ButtonLocator < Locator # :nodoc:
def locate
ButtonField.load(@session, button_element)
end
def button_element
button_elements.detect do |element|
@value.nil? ||
@ -18,37 +18,37 @@ module Webrat
matches_alt?(element)
end
end
def matches_id?(element)
(@value.is_a?(Regexp) && Webrat::XML.attribute(element, "id") =~ @value) ||
(!@value.is_a?(Regexp) && Webrat::XML.attribute(element, "id") == @value.to_s)
end
def matches_value?(element)
Webrat::XML.attribute(element, "value") =~ /^\W*#{Regexp.escape(@value.to_s)}/i
end
def matches_html?(element)
Webrat::XML.inner_html(element) =~ /#{Regexp.escape(@value.to_s)}/i
end
def matches_alt?(element)
Webrat::XML.attribute(element, "alt") =~ /^\W*#{Regexp.escape(@value.to_s)}/i
end
def button_elements
Webrat::XML.xpath_search(@dom, *ButtonField.xpath_search)
end
def error_message
"Could not find button #{@value.inspect}"
end
end
def find_button(value) #:nodoc:
ButtonLocator.new(@session, dom, value).locate!
end
end
end
end

View File

@ -2,13 +2,13 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class FieldByIdLocator < Locator # :nodoc:
def locate
Field.load(@session, field_element)
end
def field_element
field_elements.detect do |field_element|
if @value.is_a?(Regexp)
@ -18,7 +18,7 @@ module Webrat
end
end
end
def field_elements
Webrat::XML.xpath_search(@dom, *Field.xpath_search)
end
@ -26,12 +26,12 @@ module Webrat
def error_message
"Could not find field with id #{@value.inspect}"
end
end
def field_with_id(id, *field_types)
FieldByIdLocator.new(@session, dom, id, *field_types).locate!
end
end
end
end

View File

@ -3,13 +3,13 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class FieldLabeledLocator < Locator # :nodoc:
def locate
matching_labels.any? && matching_labels.detect_mapped { |label| label.field }
end
def matching_labels
matching_label_elements.sort_by do |label_element|
text(label_element).length
@ -17,21 +17,21 @@ module Webrat
Label.load(@session, label_element)
end
end
def matching_label_elements
label_elements.select do |label_element|
text(label_element) =~ /^\W*#{Regexp.escape(@value.to_s)}\b/i
end
end
def label_elements
Webrat::XML.xpath_search(@dom, Label.xpath_search)
end
def error_message
"Could not find field labeled #{@value.inspect}"
end
def text(element)
str = Webrat::XML.all_inner_text(element)
str.gsub!("\n","")
@ -39,9 +39,9 @@ module Webrat
str.squeeze!(" ")
str
end
end
# Locates a form field based on a <tt>label</tt> element in the HTML source.
# This can be useful in order to verify that a field is pre-filled with the
# correct value.
@ -51,6 +51,6 @@ module Webrat
def field_labeled(label, *field_types)
FieldLabeledLocator.new(@session, dom, label, *field_types).locate!
end
end
end

View File

@ -2,24 +2,24 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class FieldLocator < Locator # :nodoc:
def locate
FieldByIdLocator.new(@session, @dom, @value).locate ||
FieldNamedLocator.new(@session, @dom, @value, *@field_types).locate ||
FieldLabeledLocator.new(@session, @dom, @value, *@field_types).locate
end
def error_message
"Could not find field: #{@value.inspect}"
end
end
def field(*args) # :nodoc:
FieldLocator.new(@session, dom, *args).locate!
end
end
end
end

View File

@ -2,23 +2,23 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class FieldNamedLocator < Locator # :nodoc:
def locate
Field.load(@session, field_element)
end
def field_element
field_elements.detect do |field_element|
Webrat::XML.attribute(field_element, "name") == @value.to_s
end
end
def field_elements
Webrat::XML.xpath_search(@dom, *xpath_searches)
end
def xpath_searches
if @field_types.any?
@field_types.map { |field_type| field_type.xpath_search }.flatten
@ -26,16 +26,16 @@ module Webrat
Array(Field.xpath_search)
end
end
def error_message
"Could not find field named #{@value.inspect}"
end
end
def field_named(name, *field_types)
FieldNamedLocator.new(@session, dom, name, *field_types).locate!
end
end
end
end

View File

@ -2,18 +2,18 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class FormLocator < Locator # :nodoc:
def locate
Form.load(@session, form_element)
end
def form_element
Webrat::XML.css_at(@dom, "#" + @value)
end
end
end
end
end

View File

@ -3,23 +3,23 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class LabelLocator < Locator # :nodoc:
def locate
Label.load(@session, label_element)
end
def label_element
label_elements.detect do |label_element|
text(label_element) =~ /^\W*#{Regexp.escape(@value.to_s)}\b/i
end
end
def label_elements
Webrat::XML.xpath_search(@dom, Label.xpath_search)
end
def text(label_element)
str = Webrat::XML.all_inner_text(label_element)
str.gsub!("\n","")
@ -27,8 +27,8 @@ module Webrat
str.squeeze!(" ")
str
end
end
end
end
end

View File

@ -2,24 +2,24 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class LinkLocator < Locator # :nodoc:
def locate
Link.load(@session, link_element)
end
def link_element
matching_links.min { |a, b| Webrat::XML.all_inner_text(a).length <=> Webrat::XML.all_inner_text(b).length }
end
def matching_links
@matching_links ||= link_elements.select do |link_element|
matches_text?(link_element) ||
matches_id?(link_element)
end
end
def matches_text?(link)
if @value.is_a?(Regexp)
matcher = @value
@ -39,11 +39,11 @@ module Webrat
(Webrat::XML.attribute(link, "id") == @value) ? true : false
end
end
def link_elements
Webrat::XML.xpath_search(@dom, *Link.xpath_search)
end
def replace_nbsp(str)
str.gsub([0xA0].pack('U'), ' ')
end
@ -51,16 +51,16 @@ module Webrat
def replace_nbsp_ref(str)
str.gsub('&#xA0;',' ').gsub('&nbsp;', ' ')
end
def error_message
"Could not find link with text or title or id #{@value.inspect}"
end
end
def find_link(text_or_title_or_id) #:nodoc:
LinkLocator.new(@session, dom, text_or_title_or_id).locate!
end
end
end
end

View File

@ -1,6 +1,6 @@
module Webrat
module Locators
class Locator # :nodoc:
def initialize(session, dom, value, *field_types)
@ -9,12 +9,12 @@ module Webrat
@value = value
@field_types = field_types
end
def locate!
locate || raise(NotFoundError.new(error_message))
end
end
end
end
end

View File

@ -3,20 +3,20 @@ require "webrat/core/locators/locator"
module Webrat
module Locators
class SelectOptionLocator < Locator # :nodoc:
def initialize(session, dom, option_text, id_or_name_or_label)
@session = session
@dom = dom
@option_text = option_text
@id_or_name_or_label = id_or_name_or_label
end
def locate
if @id_or_name_or_label
field = FieldLocator.new(@session, @dom, @id_or_name_or_label, SelectField).locate!
field.options.detect do |o|
if @option_text.is_a?(Regexp)
Webrat::XML.inner_html(o.element) =~ @option_text
@ -32,15 +32,15 @@ module Webrat
Webrat::XML.inner_html(o) == @option_text.to_s
end
end
SelectOption.load(@session, option_element)
end
end
def option_elements
Webrat::XML.xpath_search(@dom, *SelectOption.xpath_search)
end
def error_message
if @id_or_name_or_label
"The '#{@option_text}' option was not found in the #{@id_or_name_or_label.inspect} select box"
@ -48,12 +48,12 @@ module Webrat
"Could not find option #{@option_text.inspect}"
end
end
end
def select_option(option_text, id_or_name_or_label = nil) #:nodoc:
SelectOptionLocator.new(@session, dom, option_text, id_or_name_or_label).locate!
end
end
end
end

View File

@ -1,6 +1,6 @@
module Webrat
module Logging #:nodoc:
def debug_log(message) # :nodoc:
return unless logger
logger.debug message
@ -16,6 +16,6 @@ module Webrat
nil
end
end
end
end
end

View File

@ -1,20 +1,20 @@
module Webrat
module Matchers
class HasContent #:nodoc:
def initialize(content)
@content = content
end
def matches?(stringlike)
if Webrat.configuration.parse_with_nokogiri?
@document = Webrat.nokogiri_document(stringlike)
else
@document = Webrat.hpricot_document(stringlike)
end
@element = Webrat::XML.inner_text(@document)
case @content
when String
@element.include?(@content)
@ -22,7 +22,7 @@ module Webrat
@element.match(@content)
end
end
# ==== Returns
# String:: The failure message.
def failure_message
@ -34,11 +34,11 @@ module Webrat
def negative_failure_message
"expected the following element's content to not #{content_message}:\n#{squeeze_space(@element)}"
end
def squeeze_space(inner_text)
inner_text.gsub(/^\s*$/, "").squeeze("\n")
end
def content_message
case @content
when String
@ -48,26 +48,26 @@ module Webrat
end
end
end
# Matches the contents of an HTML document with
# whatever string is supplied
def contain(content)
HasContent.new(content)
end
# Asserts that the body of the response contain
# the supplied string or regexp
def assert_contain(content)
hc = HasContent.new(content)
assert hc.matches?(response_body), hc.failure_message
end
# Asserts that the body of the response
# does not contain the supplied string or regepx
def assert_not_contain(content)
hc = HasContent.new(content)
assert !hc.matches?(response_body), hc.negative_failure_message
end
end
end
end

View File

@ -2,7 +2,7 @@ require "webrat/core/matchers/have_xpath"
module Webrat
module Matchers
class HaveSelector < HaveXpath #:nodoc:
# ==== Returns
# String:: The failure message.
@ -15,7 +15,7 @@ module Webrat
def negative_failure_message
"expected following output to omit a #{tag_inspect}:\n#{@document}"
end
def tag_inspect
options = @options.dup
count = options.delete(:count)
@ -40,9 +40,9 @@ module Webrat
ast.to_xpath
end.first
end
end
# Matches HTML content against a CSS 3 selector.
#
# ==== Parameters
@ -54,21 +54,21 @@ module Webrat
HaveSelector.new(name, attributes, &block)
end
alias_method :match_selector, :have_selector
# Asserts that the body of the response contains
# the supplied selector
def assert_have_selector(name, attributes = {}, &block)
matcher = HaveSelector.new(name, attributes, &block)
assert matcher.matches?(response_body), matcher.failure_message
end
# Asserts that the body of the response
# does not contain the supplied string or regepx
def assert_have_no_selector(name, attributes = {}, &block)
matcher = HaveSelector.new(name, attributes, &block)
assert !matcher.matches?(response_body), matcher.negative_failure_message
end
end
end
end

View File

@ -6,16 +6,16 @@ module Webrat
def have_tag(*args, &block)
have_selector(*args, &block)
end
alias_method :match_tag, :have_tag
def assert_have_tag(*args, &block)
assert_have_selector(*args, &block)
end
def assert_have_no_tag(*args, &block)
assert_have_no_selector(*args, &block)
end
end
end
end

View File

@ -3,25 +3,25 @@ require "webrat/core/xml/rexml"
module Webrat
module Matchers
class HaveXpath #:nodoc:
def initialize(expected, options = {}, &block)
@expected = expected
@options = options
@block = block
end
def matches?(stringlike, &block)
@block ||= block
matched = matches(stringlike)
if @options[:count]
matched.size == @options[:count] && (!@block || @block.call(matched))
else
matched.any? && (!@block || @block.call(matched))
end
end
def matches(stringlike)
if Webrat.configuration.parse_with_nokogiri?
nokogiri_matches(stringlike)
@ -29,7 +29,7 @@ module Webrat
rexml_matches(stringlike)
end
end
def rexml_matches(stringlike)
if REXML::Node === stringlike || Array === stringlike
@query = query.map { |q| q.gsub(%r'//', './') }
@ -49,48 +49,48 @@ module Webrat
end
end.flatten.compact
end
def nokogiri_matches(stringlike)
if Nokogiri::XML::NodeSet === stringlike
@query = query.gsub(%r'//', './')
else
@query = query
end
add_options_conditions_to(@query)
@document = Webrat::XML.document(stringlike)
@document.xpath(*@query)
end
def add_options_conditions_to(query)
add_attributes_conditions_to(query)
add_content_condition_to(query)
end
def add_attributes_conditions_to(query)
attribute_conditions = []
@options.each do |key, value|
next if [:content, :count].include?(key)
attribute_conditions << "@#{key} = #{xpath_escape(value)}"
end
if attribute_conditions.any?
query << "[#{attribute_conditions.join(' and ')}]"
end
end
def add_content_condition_to(query)
if @options[:content]
query << "[contains(., #{xpath_escape(@options[:content])})]"
end
end
def query
@expected
end
# ==== Returns
# String:: The failure message.
def failure_message
@ -102,15 +102,15 @@ module Webrat
def negative_failure_message
"expected following text to not match xpath #{@expected}:\n#{@document}"
end
protected
def xpath_escape(string)
if string.include?("'") && string.include?('"')
parts = string.split("'").map do |part|
"'#{part}'"
end
"concat(" + parts.join(", \"'\", ") + ")"
elsif string.include?("'")
"\"#{string}\""
@ -118,9 +118,9 @@ module Webrat
"'#{string}'"
end
end
end
# Matches HTML content against an XPath query
#
# ==== Parameters
@ -132,16 +132,16 @@ module Webrat
HaveXpath.new(expected, options, &block)
end
alias_method :match_xpath, :have_xpath
def assert_have_xpath(expected, options = {}, &block)
hs = HaveXpath.new(expected, options, &block)
assert hs.matches?(response_body), hs.failure_message
end
def assert_have_no_xpath(expected, options = {}, &block)
hs = HaveXpath.new(expected, options, &block)
assert !hs.matches?(response_body), hs.negative_failure_message
end
end
end
end

View File

@ -10,15 +10,15 @@ module Webrat
RUBY
end
end
def webrat
webrat_session
end
def webrat_session
@_webrat_session ||= ::Webrat.session_class.new(self)
end
# all of these methods delegate to the @session, which should
# be created transparently.
#
@ -31,7 +31,7 @@ module Webrat
:header, :http_accept, :basic_auth,
:save_and_open_page,
:fills_in, :fill_in,
:checks, :check,
:checks, :check,
:unchecks, :uncheck,
:chooses, :choose,
:selects, :select,
@ -47,15 +47,15 @@ module Webrat
:select_option,
:set_hidden_field, :submit_form,
:request_page, :current_dom,
:response_body,
:response_body,
:selects_date, :selects_time, :selects_datetime,
:select_date, :select_time, :select_datetime,
:field_by_xpath,
:field_with_id,
:selenium,
:simulate, :automate
end
end
end

View File

@ -1,6 +1,6 @@
module Webrat #:nodoc:
module MIME #:nodoc:
def self.mime_type(string_or_symbol) #:nodoc:
if string_or_symbol.is_a?(String)
string_or_symbol
@ -24,6 +24,6 @@ module Webrat #:nodoc:
end
end
end
end
end
end

View File

@ -2,21 +2,21 @@ module Webrat
module SaveAndOpenPage
# Saves the page out to RAILS_ROOT/tmp/ and opens it in the default
# web browser if on OS X. Useful for debugging.
#
#
# Example:
# save_and_open_page
def save_and_open_page
return unless File.exist?(saved_page_dir)
filename = "#{saved_page_dir}/webrat-#{Time.now.to_i}.html"
File.open(filename, "w") do |f|
f.write rewrite_css_and_image_references(response_body)
end
open_in_browser(filename)
end
def open_in_browser(path) # :nodoc
platform = ruby_platform
if platform =~ /cygwin/ || platform =~ /win32/
@ -25,26 +25,26 @@ module Webrat
`open #{path}`
end
end
def rewrite_css_and_image_references(response_html) # :nodoc:
return response_html unless doc_root
response_html.gsub(/"\/(stylesheets|images)/, doc_root + '/\1')
end
def saved_page_dir #:nodoc:
File.expand_path(".")
end
def doc_root #:nodoc:
nil
end
private
# accessor for testing
def ruby_platform
RUBY_PLATFORM
end
end
end
end

View File

@ -6,36 +6,36 @@ module Webrat
# An HTML element (link, button, field, etc.) that Webrat expected was not found on the page
class NotFoundError < WebratError
end
class Scope
include Logging
include Locators
def self.from_page(session, response, response_body) #:nodoc:
new(session) do
@response = response
@response_body = response_body
end
end
def self.from_scope(session, scope, selector) #:nodoc:
new(session) do
@scope = scope
@selector = selector
end
end
attr_reader :session
def initialize(session, &block) #:nodoc:
@session = session
instance_eval(&block) if block_given?
if @selector && scoped_dom.nil?
raise Webrat::NotFoundError.new("The scope was not found on the page: #{@selector.inspect}")
end
end
# Verifies an input field or textarea exists on the current page, and stores a value for
# it which will be sent when the form is submitted.
#
@ -53,7 +53,7 @@ module Webrat
end
webrat_deprecate :fills_in, :fill_in
# Verifies that a hidden field exists on the current page and sets
# the value to that given by the <tt>:to</tt> option.
#
@ -63,7 +63,7 @@ module Webrat
field = locate_field(field_locator, HiddenField)
field.set(options[:to])
end
# Verifies that an input checkbox exists on the current page and marks it
# as checked, so that the value will be submitted with the form.
#
@ -74,7 +74,7 @@ module Webrat
end
webrat_deprecate :checks, :check
# Verifies that an input checkbox exists on the current page and marks it
# as unchecked, so that the value will not be submitted with the form.
#
@ -85,7 +85,7 @@ module Webrat
end
webrat_deprecate :unchecks, :uncheck
# Verifies that an input radio button exists on the current page and marks it
# as checked, so that the value will be submitted with the form.
#
@ -96,7 +96,7 @@ module Webrat
end
webrat_deprecate :chooses, :choose
# Verifies that a an option element exists on the current page with the specified
# text. You can optionally restrict the search to a specific select list by
# assigning <tt>options[:from]</tt> the value of the select list's name or
@ -111,7 +111,7 @@ module Webrat
end
webrat_deprecate :selects, :select
DATE_TIME_SUFFIXES = {
:year => '1i',
:month => '2i',
@ -120,9 +120,9 @@ module Webrat
:minute => '5i'
}
# Verifies that date elements (year, month, day) exist on the current page
# Verifies that date elements (year, month, day) exist on the current page
# with the specified values. You can optionally restrict the search to a specific
# date's elements by assigning <tt>options[:from]</tt> the value of the date's
# date's elements by assigning <tt>options[:from]</tt> the value of the date's
# label. Selects all the date elements with date provided. The date provided may
# be a string or a Date/Time object.
#
@ -136,15 +136,15 @@ module Webrat
# select_date Date.parse("December 25, 2000"), :from => "Event"
# select_date "April 26, 1982", :id_prefix => 'birthday'
def select_date(date_to_select, options ={})
date = date_to_select.is_a?(Date) || date_to_select.is_a?(Time) ?
date_to_select : Date.parse(date_to_select)
date = date_to_select.is_a?(Date) || date_to_select.is_a?(Time) ?
date_to_select : Date.parse(date_to_select)
id_prefix = locate_id_prefix(options) do
year_field = FieldByIdLocator.new(@session, dom, /(.*?)_#{DATE_TIME_SUFFIXES[:year]}$/).locate
raise NotFoundError.new("No date fields were found") unless year_field && year_field.id =~ /(.*?)_1i/
$1
end
select date.year, :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:year]}"
select date.strftime('%B'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:month]}"
select date.day, :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:day]}"
@ -152,9 +152,9 @@ module Webrat
webrat_deprecate :selects_date, :select_date
# Verifies that time elements (hour, minute) exist on the current page
# Verifies that time elements (hour, minute) exist on the current page
# with the specified values. You can optionally restrict the search to a specific
# time's elements by assigning <tt>options[:from]</tt> the value of the time's
# time's elements by assigning <tt>options[:from]</tt> the value of the time's
# label. Selects all the time elements with date provided. The time provided may
# be a string or a Time object.
#
@ -164,28 +164,28 @@ module Webrat
#
# Note: Just like Rails' time_select helper this assumes the form is using
# 24 hour select boxes, and not 12 hours with AM/PM.
#
#
# Examples:
# select_time "9:30"
# select_date "3:30PM", :from => "Party Time"
# select_date Time.parse("10:00PM"), :from => "Event"
# select_date "10:30AM", :id_prefix => 'meeting'
def select_time(time_to_select, options ={})
time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select)
time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select)
id_prefix = locate_id_prefix(options) do
hour_field = FieldByIdLocator.new(@session, dom, /(.*?)_#{DATE_TIME_SUFFIXES[:hour]}$/).locate
raise NotFoundError.new("No time fields were found") unless hour_field && hour_field.id =~ /(.*?)_4i/
$1
end
select time.hour.to_s.rjust(2,'0'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:hour]}"
select time.min.to_s.rjust(2,'0'), :from => "#{id_prefix}_#{DATE_TIME_SUFFIXES[:minute]}"
end
webrat_deprecate :selects_time, :select_time
# Verifies and selects all the date and time elements on the current page.
# Verifies and selects all the date and time elements on the current page.
# See #select_time and #select_date for more details and available options.
#
# Examples:
@ -194,16 +194,16 @@ module Webrat
# select_datetime Time.parse("December 25, 2000 15:30"), :from => "Event"
# select_datetime "April 26, 1982 5:50PM", :id_prefix => 'birthday'
def select_datetime(time_to_select, options ={})
time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select)
time = time_to_select.is_a?(Time) ? time_to_select : Time.parse(time_to_select)
options[:id_prefix] ||= (options[:from] ? FieldByIdLocator.new(@session, dom, options[:from]).locate : nil)
select_date time, options
select_time time, options
end
webrat_deprecate :selects_datetime, :select_datetime
# Verifies that an input file field exists on the current page and sets
# its value to the given +file+, so that the file will be uploaded
# along with the form. An optional <tt>content_type</tt> may be given.
@ -229,13 +229,13 @@ module Webrat
def click_area(area_name)
find_area(area_name).click
end
webrat_deprecate :clicks_area, :click_area
# Issues a request for the URL pointed to by a link on the current page,
# follows any redirects, and verifies the final page load was successful.
#
# click_link has very basic support for detecting Rails-generated
#
# click_link has very basic support for detecting Rails-generated
# JavaScript onclick handlers for PUT, POST and DELETE links, as well as
# CSRF authenticity tokens if they are present.
#
@ -243,15 +243,15 @@ module Webrat
#
# Passing a :method in the options hash overrides the HTTP method used
# for making the link request
#
#
# It will try to find links by (in order of precedence):
# innerHTML, with simple &nbsp; handling
# title
# id
#
#
# innerHTML and title are matchable by text subtring or Regexp
# id is matchable by full text equality or Regexp
#
#
# Example:
# click_link "Sign up"
# click_link "Sign up", :javascript => false
@ -261,7 +261,7 @@ module Webrat
end
webrat_deprecate :clicks_link, :click_link
# Verifies that a submit button exists for the form, then submits the form, follows
# any redirects, and verifies the final page was successful.
#
@ -288,38 +288,38 @@ module Webrat
def submit_form(id)
FormLocator.new(@session, dom, id).locate.submit
end
def dom # :nodoc:
return @dom if @dom
if @selector
@dom = scoped_dom
else
@dom = page_dom
end
return @dom
end
protected
def page_dom #:nodoc:
return @response.dom if @response.respond_to?(:dom)
if @session.xml_content_type?
dom = Webrat::XML.xml_document(@response_body)
else
dom = Webrat::XML.html_document(@response_body)
end
Webrat.define_dom_method(@response, dom)
return dom
end
def scoped_dom
Webrat::XML.css_at(@scope.dom, @selector)
end
def locate_field(field_locator, *field_types) #:nodoc:
if field_locator.is_a?(Field)
field_locator
@ -327,10 +327,10 @@ module Webrat
field(field_locator, *field_types)
end
end
def locate_id_prefix(options, &location_strategy) #:nodoc:
return options[:id_prefix] if options[:id_prefix]
if options[:from]
if (label = LabelLocator.new(@session, dom, options[:from]).locate)
label.for_id
@ -341,10 +341,10 @@ module Webrat
yield
end
end
def forms #:nodoc:
@forms ||= Form.load_all(@session, dom)
end
end
end

View File

@ -11,7 +11,7 @@ module Webrat
class InfiniteRedirectError < WebratError
end
def self.session_class
case Webrat.configuration.mode
when :rails
@ -77,7 +77,7 @@ For example:
def doc_root #:nodoc:
nil
end
def header(key, value)
@custom_headers[key] = value
end
@ -122,13 +122,13 @@ For example:
return response
end
def check_for_infinite_redirects
if current_url == response_location
@_identical_redirect_count ||= 0
@_identical_redirect_count += 1
end
if infinite_redirect_limit_exceeded?
raise InfiniteRedirectError.new("#{Webrat.configuration.infinite_redirect_limit} redirects to the same URL (#{current_url.inspect})")
end
@ -138,7 +138,7 @@ For example:
Webrat.configuration.infinite_redirect_limit &&
(@_identical_redirect_count || 0) > Webrat.configuration.infinite_redirect_limit
end
def success_code? #:nodoc:
(200..499).include?(response_code)
end
@ -154,7 +154,7 @@ For example:
response_location_host_domain = response_location_host.split('.')[-2..-1].join('.') rescue response_location_host
current_host_domain == response_location_host_domain
end
#easy helper to pull out where we were redirected to
def redirected_to
redirect? ? response_location : nil
@ -276,6 +276,6 @@ For example:
@_scopes = nil
@_page_scope = nil
end
end
end

View File

@ -4,7 +4,7 @@ require "webrat/core/xml/rexml"
module Webrat #:nodoc:
module XML #:nodoc:
def self.document(stringlike) #:nodoc:
if Webrat.configuration.parse_with_nokogiri?
Webrat.nokogiri_document(stringlike)
@ -12,7 +12,7 @@ module Webrat #:nodoc:
Webrat.rexml_document(Webrat.hpricot_document(stringlike).to_html)
end
end
def self.html_document(stringlike) #:nodoc:
if Webrat.configuration.parse_with_nokogiri?
Webrat.html_nokogiri_document(stringlike)
@ -20,7 +20,7 @@ module Webrat #:nodoc:
Webrat.rexml_document(Webrat.hpricot_document(stringlike).to_html)
end
end
def self.xml_document(stringlike) #:nodoc:
if Webrat.configuration.parse_with_nokogiri?
Webrat.xml_nokogiri_document(stringlike)
@ -36,7 +36,7 @@ module Webrat #:nodoc:
element.to_s
end
end
def self.inner_html(element)
if Webrat.configuration.parse_with_nokogiri?
element.inner_html
@ -44,7 +44,7 @@ module Webrat #:nodoc:
element.text
end
end
def self.all_inner_text(element)
if Webrat.configuration.parse_with_nokogiri?
element.inner_text
@ -52,7 +52,7 @@ module Webrat #:nodoc:
Hpricot(element.to_s).children.first.inner_text
end
end
def self.inner_text(element)
if Webrat.configuration.parse_with_nokogiri?
element.inner_text
@ -64,7 +64,7 @@ module Webrat #:nodoc:
end
end
end
def self.xpath_to(element)
if Webrat.configuration.parse_with_nokogiri?
element.path
@ -72,25 +72,25 @@ module Webrat #:nodoc:
element.xpath
end
end
def self.attribute(element, attribute_name)
return element[attribute_name] if element.is_a?(Hash)
if Webrat.configuration.parse_with_nokogiri?
element[attribute_name]
else
element.attributes[attribute_name]
end
end
def self.xpath_at(*args)
xpath_search(*args).first
end
def self.css_at(*args)
css_search(*args).first
end
def self.xpath_search(element, *searches)
searches.flatten.map do |search|
if Webrat.configuration.parse_with_nokogiri?
@ -100,16 +100,16 @@ module Webrat #:nodoc:
end
end.flatten.compact
end
def self.css_search(element, *searches) #:nodoc:
xpath_search(element, css_to_xpath(*searches))
end
def self.css_to_xpath(*selectors)
selectors.map do |rule|
Nokogiri::CSS.xpath_for(rule, :prefix => ".//")
end.flatten.uniq
end
end
end
end

View File

@ -1,5 +1,5 @@
module Webrat
def self.hpricot_document(stringlike)
return stringlike.dom if stringlike.respond_to?(:dom)
@ -15,5 +15,5 @@ module Webrat
Hpricot(stringlike.to_s)
end
end
end
end

View File

@ -1,10 +1,10 @@
require "webrat/core_extensions/meta_class"
module Webrat
def self.nokogiri_document(stringlike) #:nodoc:
return stringlike.dom if stringlike.respond_to?(:dom)
if Nokogiri::HTML::Document === stringlike
stringlike
elsif Nokogiri::XML::NodeSet === stringlike
@ -17,10 +17,10 @@ module Webrat
Nokogiri::HTML(stringlike.to_s)
end
end
def self.html_nokogiri_document(stringlike) #:nodoc:
return stringlike.dom if stringlike.respond_to?(:dom)
if Nokogiri::HTML::Document === stringlike
stringlike
elsif Nokogiri::XML::NodeSet === stringlike
@ -33,10 +33,10 @@ module Webrat
Nokogiri::HTML(stringlike.to_s)
end
end
def self.xml_nokogiri_document(stringlike) #:nodoc:
return stringlike.dom if stringlike.respond_to?(:dom)
if Nokogiri::HTML::Document === stringlike
stringlike
elsif Nokogiri::XML::NodeSet === stringlike
@ -49,20 +49,20 @@ module Webrat
Nokogiri::XML(stringlike.to_s)
end
end
def self.define_dom_method(object, dom) #:nodoc:
object.meta_class.send(:define_method, :dom) do
dom
end
end
end
module Nokogiri #:nodoc:
module CSS #:nodoc:
class XPathVisitor #:nodoc:
def visit_pseudo_class_text(node) #:nodoc:
"@type='text'"
end
@ -70,7 +70,7 @@ module Nokogiri #:nodoc:
def visit_pseudo_class_password(node) #:nodoc:
"@type='password'"
end
end
end
end
end

View File

@ -1,5 +1,5 @@
module Webrat
def self.rexml_document(stringlike)
stringlike = stringlike.body.to_s if stringlike.respond_to?(:body)
@ -20,5 +20,5 @@ module Webrat
end
end
end
end
end

View File

@ -12,7 +12,7 @@ class Object #:nodoc:
def blank?
respond_to?(:empty?) ? empty? : !self
end
# An object is present if it's not blank.
def present?
!blank?

View File

@ -5,4 +5,4 @@ class Module #:nodoc:
__send__(new_method_name, *args)
end
end
end
end

View File

@ -1,12 +1,12 @@
class Array #:nodoc:
def detect_mapped
each do |element|
result = yield element
return result if result
end
return nil
end
end
end

View File

@ -3,4 +3,4 @@ class ::Object #:nodoc:
class << self; self end
end
end

View File

@ -1,27 +1,27 @@
class TCPSocket
def self.wait_for_service_with_timeout(options)
start_time = Time.now
until listening_service?(options)
verbose_wait
if options[:timeout] && (Time.now > start_time + options[:timeout])
raise SocketError.new("Socket did not open within #{options[:timeout]} seconds")
end
end
end
def self.wait_for_service_termination_with_timeout(options)
start_time = Time.now
while listening_service?(options)
verbose_wait
if options[:timeout] && (Time.now > start_time + options[:timeout])
raise SocketError.new("Socket did not terminate within #{options[:timeout]} seconds")
end
end
end
end
end

View File

@ -2,14 +2,14 @@ require "mechanize"
module Webrat #:nodoc:
class MechanizeSession < Session #:nodoc:
attr_accessor :response
alias :page :response
def request_page(url, http_method, data) #:nodoc:
super(absolute_url(url), http_method, data)
end
def get(url, data, headers_argument_not_used = nil)
@response = mechanize.get(url, data)
end
@ -26,7 +26,7 @@ module Webrat #:nodoc:
end
@response = mechanize.post(url, post_data)
end
def response_body
@response.content
end
@ -34,13 +34,13 @@ module Webrat #:nodoc:
def response_code
@response.code.to_i
end
def mechanize
@mechanize ||= WWW::Mechanize.new
end
def_delegators :mechanize, :basic_auth
def absolute_url(url) #:nodoc:
current_host, current_path = split_current_url
if url =~ Regexp.new('^https?://')
@ -53,13 +53,13 @@ module Webrat #:nodoc:
url
end
end
private
def split_current_url
current_url =~ Regexp.new('^(https?://[^/]+)(/.*)?')
[Regexp.last_match(1), Regexp.last_match(2)]
end
def absolute_path(current_path, url)
levels_up = url.split('/').find_all { |x| x == '..' }.size
ancestor = if current_path.nil?

View File

@ -6,4 +6,4 @@ require "webrat"
Webrat.configure do |config|
config.mode = :merb
end
end

View File

@ -10,36 +10,36 @@ require "merb-core"
module Webrat
class MerbSession < Session #:nodoc:
include Merb::Test::MakeRequest
attr_accessor :response
def get(url, data, headers = nil)
do_request(url, data, headers, "GET")
end
def post(url, data, headers = nil)
do_request(url, data, headers, "POST")
end
def put(url, data, headers = nil)
do_request(url, data, headers, "PUT")
end
def delete(url, data, headers = nil)
do_request(url, data, headers, "DELETE")
end
def response_body
@response.body.to_s
end
def response_code
@response.status
end
def do_request(url, data, headers, method)
@response = request(url,
:params => (data && data.any?) ? data : nil,
@response = request(url,
:params => (data && data.any?) ? data : nil,
:headers => headers,
:method => method)
end

View File

@ -7,7 +7,7 @@ require "action_controller/record_identifier"
module Webrat
class RailsSession < Session #:nodoc:
include ActionController::RecordIdentifier
# The Rails version of within supports passing in a model and Webrat
# will apply a scope based on Rails' dom_id for that model.
#
@ -22,7 +22,7 @@ module Webrat
super('#' + dom_id(selector_or_object), &block)
end
end
def doc_root
File.expand_path(File.join(RAILS_ROOT, 'public'))
end

View File

@ -1,6 +1,6 @@
# Supports using the matchers in controller, helper, and view specs if you're
# using rspec-rails. Just add a require statement to spec/spec_helper.rb or env.rb:
#
#
# require 'webrat/rspec-rails'
#
require "webrat/core/matchers"
@ -10,4 +10,4 @@ Spec::Runner.configure do |config|
config.include(Webrat::Matchers, :type => :controller)
config.include(Webrat::Matchers, :type => :helper)
config.include(Webrat::Matchers, :type => :view)
end
end

View File

@ -1,8 +1,8 @@
module Webrat
module Selenium
class ApplicationServer
def self.boot
case Webrat.configuration.application_framework
when :sinatra
@ -30,25 +30,25 @@ For example:
STR
end
end
def boot
start
wait
stop_at_exit
end
def stop_at_exit
at_exit do
stop
end
end
def wait
$stderr.print "==> Waiting for #{Webrat.configuration.application_framework} application server on port #{Webrat.configuration.application_port}... "
wait_for_socket
$stderr.print "Ready!\n"
end
def wait_for_socket
silence_stream(STDOUT) do
TCPSocket.wait_for_service_with_timeout \
@ -64,8 +64,8 @@ For example:
FileUtils.mkdir_p File.expand_path(file_path)
File.expand_path("#{file_path}/#{pid_file_name}")
end
end
end
end
end

View File

@ -1,4 +1,4 @@
require "webrat/selenium/matchers/have_xpath"
require "webrat/selenium/matchers/have_selector"
# require "webrat/selenium/matchers/have_tag"
require "webrat/selenium/matchers/have_content"
require "webrat/selenium/matchers/have_content"

View File

@ -5,14 +5,14 @@ module Webrat
def initialize(content)
@content = content
end
def matches?(response)
if @content.is_a?(Regexp)
text_finder = "regexp:#{@content.source}"
else
text_finder = @content
end
response.session.wait_for do
response.selenium.is_text_present(text_finder)
end
@ -47,7 +47,7 @@ module Webrat
def contain(content)
HasContent.new(content)
end
# Asserts that the body of the response contain
# the supplied string or regexp
def assert_contain(content)
@ -63,4 +63,4 @@ module Webrat
end
end
end
end
end

View File

@ -5,7 +5,7 @@ module Webrat
def initialize(expected)
@expected = expected
end
def matches?(response)
response.session.wait_for do
response.selenium.is_element_present("css=#{@expected}")
@ -26,11 +26,11 @@ module Webrat
"expected following text to not match selector #{@expected}:\n#{@document}"
end
end
def have_selector(content)
HaveSelector.new(content)
end
# Asserts that the body of the response contains
# the supplied selector
def assert_have_selector(expected)
@ -46,4 +46,4 @@ module Webrat
end
end
end
end
end

View File

@ -1,72 +1,72 @@
module Webrat
module Selenium
module Matchers
class HaveTag < HaveSelector #:nodoc:
# ==== Returns
# String:: The failure message.
def failure_message
"expected following output to contain a #{tag_inspect} tag:\n#{@document}"
end
# ==== Returns
# String:: The failure message to be displayed in negative matches.
def negative_failure_message
"expected following output to omit a #{tag_inspect}:\n#{@document}"
end
def tag_inspect
options = @expected.last.dup
content = options.delete(:content)
html = "<#{@expected.first}"
options.each do |k,v|
html << " #{k}='#{v}'"
end
if content
html << ">#{content}</#{@expected.first}>"
else
html << "/>"
end
html
end
def query
options = @expected.last.dup
selector = @expected.first.to_s
selector << ":contains('#{options.delete(:content)}')" if options[:content]
options.each do |key, value|
selector << "[#{key}='#{value}']"
end
Nokogiri::CSS.parse(selector).map { |ast| ast.to_xpath }
end
end
def have_tag(name, attributes = {}, &block)
HaveTag.new([name, attributes], &block)
end
alias_method :match_tag, :have_tag
# Asserts that the body of the response contains
# the supplied tag with the associated selectors
def assert_have_tag(name, attributes = {})
ht = HaveTag.new([name, attributes])
assert ht.matches?(response), ht.failure_message
end
# Asserts that the body of the response
# does not contain the supplied string or regepx
def assert_have_no_tag(name, attributes = {})
ht = HaveTag.new([name, attributes])
assert !ht.matches?(response), ht.negative_failure_message
end
end
end
end
end

View File

@ -5,7 +5,7 @@ module Webrat
def initialize(expected)
@expected = expected
end
def matches?(response)
response.session.wait_for do
response.selenium.is_element_present("xpath=#{@expected}")
@ -26,11 +26,11 @@ module Webrat
"expected following text to not match xpath #{@expected}:\n#{@document}"
end
end
def have_xpath(xpath)
HaveXpath.new(xpath)
end
def assert_have_xpath(expected)
hs = HaveXpath.new(expected)
assert hs.matches?(response), hs.failure_message
@ -42,4 +42,4 @@ module Webrat
end
end
end
end
end

View File

@ -1,12 +1,12 @@
module Webrat
module Selenium
class MerbApplicationServer < ApplicationServer
def start
system start_command
end
def stop
silence_stream(STDOUT) do
pid = File.read(pid_file)
@ -14,7 +14,7 @@ module Webrat
FileUtils.rm_f pid_file
end
end
def fail
$stderr.puts
$stderr.puts
@ -25,11 +25,11 @@ module Webrat
$stderr.puts " #{start_command}"
exit
end
def pid_file
"log/merb.#{Webrat.configuration.application_port}.pid"
end
def start_command
"#{merb_command} -d -p #{Webrat.configuration.application_port} -e #{Webrat.configuration.application_environment}"
end
@ -41,8 +41,8 @@ module Webrat
merb_cmd = 'merb'
end
end
end
end
end
end

View File

@ -1,18 +1,18 @@
module Webrat
module Selenium
class RailsApplicationServer < ApplicationServer
def start
system start_command
end
def stop
silence_stream(STDOUT) do
system stop_command
end
end
def fail
$stderr.puts
$stderr.puts
@ -23,11 +23,11 @@ module Webrat
$stderr.puts " #{start_command}"
exit
end
def pid_file
prepare_pid_file("#{RAILS_ROOT}/tmp/pids", "mongrel_selenium.pid")
end
def start_command
"mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{Webrat.configuration.application_port} --environment=#{Webrat.configuration.application_environment} --pid #{pid_file} &"
end
@ -35,8 +35,8 @@ module Webrat
def stop_command
"mongrel_rails stop -c #{RAILS_ROOT} --pid #{pid_file}"
end
end
end
end
end

View File

@ -1,49 +1,49 @@
module Webrat
module Selenium
class SeleniumRCServer
def self.boot
new.boot
end
def boot
return if selenium_grid?
start
wait
stop_at_exit
end
def start
silence_stream(STDOUT) do
remote_control.start :background => true
end
end
def stop_at_exit
at_exit do
stop
end
end
def remote_control
return @remote_control if @remote_control
@remote_control = ::Selenium::RemoteControl::RemoteControl.new("0.0.0.0", Webrat.configuration.selenium_server_port, 5)
@remote_control.jar_file = jar_path
return @remote_control
end
def jar_path
File.expand_path(__FILE__ + "../../../../../vendor/selenium-server.jar")
end
def selenium_grid?
Webrat.configuration.selenium_server_address
end
def wait
$stderr.print "==> Waiting for Selenium RC server on port #{Webrat.configuration.selenium_server_port}... "
wait_for_socket
@ -51,7 +51,7 @@ module Webrat
rescue SocketError
fail
end
def wait_for_socket
silence_stream(STDOUT) do
TCPSocket.wait_for_service_with_timeout \
@ -60,21 +60,21 @@ module Webrat
:timeout => 15 # seconds
end
end
def fail
$stderr.puts
$stderr.puts
$stderr.puts "==> Failed to boot the Selenium RC server... exiting!"
exit
end
def stop
silence_stream(STDOUT) do
::Selenium::RemoteControl::RemoteControl.new("0.0.0.0", Webrat.configuration.selenium_server_port, 5).stop
end
end
end
end
end

View File

@ -181,7 +181,7 @@ module Webrat
end
protected
def silence_stream(stream)
old_stream = stream.dup
stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
@ -208,7 +208,7 @@ module Webrat
$browser = ::Selenium::Client::Driver.new(Webrat.configuration.selenium_server_address || "localhost",
Webrat.configuration.selenium_server_port, Webrat.configuration.selenium_browser_key, "http://#{Webrat.configuration.application_address}:#{Webrat.configuration.application_port}")
$browser.set_speed(0) unless Webrat.configuration.selenium_server_address
at_exit do
silence_stream(STDOUT) do
$browser.stop

View File

@ -1,15 +1,15 @@
module Webrat
module Selenium
class SinatraApplicationServer < ApplicationServer
def start
fork do
File.open('rack.pid', 'w') { |fp| fp.write Process.pid }
exec 'rackup', File.expand_path(Dir.pwd + '/config.ru'), '-p', Webrat.configuration.application_port.to_s
end
end
def stop
silence_stream(STDOUT) do
pid = File.read(pid_file)
@ -17,19 +17,19 @@ module Webrat
FileUtils.rm_f pid_file
end
end
def fail
$stderr.puts
$stderr.puts
$stderr.puts "==> Failed to boot the Sinatra application server... exiting!"
exit
end
def pid_file
prepare_pid_file(Dir.pwd, 'rack.pid')
end
end
end
end
end

View File

@ -31,4 +31,4 @@ module Webrat #:nodoc:
def delete(url, data, headers = nil)
end
end
end
end

View File

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

View File

@ -1,5 +1,5 @@
class Exceptions < Merb::Controller
# handle NotFound exceptions (404)
def not_found
render :format => :html
@ -10,4 +10,4 @@ class Exceptions < Merb::Controller
render :format => :html
end
end
end

View File

@ -1,18 +1,18 @@
class Testing < Application
def show_form
render
end
def submit_form
end
def internal_redirect
redirect "/"
end
def external_redirect
redirect "http://google.com"
end
end
end

View File

@ -1,25 +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
end

View File

@ -8,4 +8,4 @@ end
use Merb::Rack::Static, Merb.dir_for(:public)
# this is our main merb application
run Merb::Rack::Application.new
run Merb::Rack::Application.new

View File

@ -10,7 +10,7 @@
#
# 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").
@ -30,4 +30,4 @@ Merb::Router.prepare do
match("/").to(:controller => "testing", :action => "show_form")
match("/internal_redirect").to(:controller => "testing", :action => "internal_redirect")
match("/external_redirect").to(:controller => "testing", :action => "external_redirect")
end
end

View File

@ -21,4 +21,4 @@ end
Webrat.configure do |config|
config.mode = :merb
end
end

View File

@ -19,7 +19,7 @@ describe "Webrat" do
response.status.should == 200
response.should contain("Webrat Form")
end
it "should check the value of a field" do
visit "/"
field_labeled("Prefilled").value.should == "text"
@ -29,4 +29,4 @@ describe "Webrat" do
response = visit "/external_redirect"
response.status.should == 302
end
end
end

View File

@ -12,9 +12,9 @@ if File.directory?(gems_dir)
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
@ -28,4 +28,4 @@ if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
end
gem '<%= @spec.name %>', version
load '<%= bin_file_name %>'
load '<%= bin_file_name %>'

View File

@ -7,21 +7,21 @@ 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)
@ -34,31 +34,31 @@ module Gem
@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
end

View File

@ -2,12 +2,12 @@ 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]
@ -25,19 +25,19 @@ end)
class ::Gem::Uninstaller
def self._with_silent_ui
ui = Gem::DefaultUserInteraction.ui
ui = Gem::DefaultUserInteraction.ui
def ui.say(str)
puts "- #{str}"
end
yield
class << Gem::DefaultUserInteraction.ui
remove_method :say
end
end
end
def self._uninstall(source_index, name, op, version)
unless source_index.find_name(name, "#{op} #{version}").empty?
uninstaller = Gem::Uninstaller.new(
@ -50,7 +50,7 @@ class ::Gem::Uninstaller
_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)
@ -67,14 +67,14 @@ 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
@ -83,9 +83,9 @@ 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")
@ -121,4 +121,4 @@ class ::Gem::Specification
end
specs + specs.map {|s| s.recursive_dependencies(self, index)}.flatten.uniq
end
end
end

View File

@ -18,7 +18,7 @@ module Thor::Tasks
@dependencies << [name, versions]
end
end
class Gem < Thor
def full_list
@idx.load_gems_in("gems/specifications")
@ -34,7 +34,7 @@ module Thor::Tasks
[spec] + deps
end.flatten.uniq
end
def rescue_failures(error = StandardError, prc = nil)
begin
yield
@ -67,12 +67,12 @@ module Thor::Tasks
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",
@ -90,4 +90,4 @@ module Thor::Tasks
end
end
end
end
end

View File

@ -5,34 +5,34 @@ class String
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

View File

@ -7,9 +7,9 @@ class ApplicationController < ActionController::Base
# 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
# 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").
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
end

View File

@ -12,28 +12,28 @@ class WebratController < ApplicationController
def submit
render :text => "OK <a href='/' id='link_id'>Test Link Text</a>"
end
def internal_redirect
redirect_to submit_path
end
def infinite_redirect
redirect_to infinite_redirect_path
end
def external_redirect
redirect_to "http://google.com"
end
def before_redirect_form
end
def redirect_to_show_params
redirect_to show_params_path(:custom_param => "123")
end
def show_params
render :text => params.to_json
end
end
end

View File

@ -14,4 +14,4 @@ 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
config.action_mailer.raise_delivery_errors = false

View File

@ -1,6 +1,6 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# 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'

View File

@ -14,4 +14,4 @@ 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
ActiveSupport.escape_html_entities_in_json = false

View File

@ -4,11 +4,11 @@ ActionController::Routing::Routes.draw do |map|
webrat.internal_redirect "/internal_redirect", :action => "internal_redirect"
webrat.external_redirect "/external_redirect", :action => "external_redirect"
webrat.infinite_redirect "/infinite_redirect", :action => "infinite_redirect"
webrat.before_redirect_form "/before_redirect_form", :action => "before_redirect_form"
webrat.redirect_to_show_params "/redirect_to_show_params", :action => "redirect_to_show_params"
webrat.show_params "/show_params", :action => "show_params"
webrat.root :action => "form"
end
end

View File

@ -66,13 +66,13 @@ class WebratTest < ActionController::IntegrationTest
visit root_path
assert_have_selector "h1"
end
test "should detect infinite redirects" do
assert_raises Webrat::InfiniteRedirectError do
visit infinite_redirect_path
end
end
# test "should be able to assert have tag" do
# visit root_path
# assert_have_tag "h1"

View File

@ -22,4 +22,4 @@ Dispatcher.class_eval do
def self.failsafe_response(output, status, exception = nil)
raise exception
end
end
end

View File

@ -24,7 +24,7 @@ describe Webrat::Configuration do
config = Webrat::Configuration.new
config.should open_error_files
end
it "should detect infinite redirects after 10" do
config = Webrat::Configuration.new
config.infinite_redirect_limit.should == 10
@ -43,7 +43,7 @@ describe Webrat::Configuration do
Webrat.configure do |config|
config.open_error_files = false
end
Webrat.configure do |config|
config.selenium_server_port = 1234
end
@ -52,7 +52,7 @@ describe Webrat::Configuration do
config.should_not open_error_files
config.selenium_server_port.should == 1234
end
[:rails,
:selenium,
:rack,
@ -70,7 +70,7 @@ describe Webrat::Configuration do
config.should_receive(:require).with("webrat/merb_session")
config.mode = :merb
end
describe "Selenium" do
before :each do
@config = Webrat::Configuration.new

View File

@ -8,13 +8,13 @@ module Webrat
<input type='checkbox' checked='checked' />
</html>
HTML
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
checkbox = CheckboxField.new(nil, element)
checkbox.inspect.should =~ /#<Webrat::CheckboxField @element=<input type=['"]checkbox['"] checked(=['"]checked['"])?\/?>>/
end
end
describe CheckboxField do
it "should say it is checked if it is" do
html = <<-HTML
@ -22,7 +22,7 @@ module Webrat
<input type='checkbox' checked='checked' />
</html>
HTML
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
checkbox = CheckboxField.new(nil, element)
checkbox.should be_checked
@ -34,13 +34,13 @@ module Webrat
<input type='checkbox' />
</html>
HTML
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
checkbox = CheckboxField.new(nil, element)
checkbox.should_not be_checked
end
end
describe RadioField do
it "should say it is checked if it is" do
html = <<-HTML
@ -48,7 +48,7 @@ module Webrat
<input type='radio' checked='checked' />
</html>
HTML
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
radio_button = RadioField.new(nil, element)
radio_button.should be_checked
@ -58,8 +58,8 @@ module Webrat
html = <<-HTML
<html><input type='radio' /></html>
HTML
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
element = Webrat::XML.css_search(Webrat::XML.document(html), "input").first
radio_button = RadioField.new(nil, element)
radio_button.should_not be_checked
end

View File

@ -7,18 +7,18 @@ describe Webrat::Link do
webrat_session = mock(Webrat::TestSession)
@link_text_with_nbsp = 'Link' + [0xA0].pack("U") + 'Text'
end
it "should pass through relative urls" do
link = Webrat::Link.new(webrat_session, {"href" => "/path"})
webrat_session.should_receive(:request_page).with("/path", :get, {})
link.click
end
it "shouldnt put base url onto " do
url = "https://www.example.com/path"
webrat_session.should_receive(:request_page).with(url, :get, {})
link = Webrat::Link.new(webrat_session, {"href" => url})
link.click
end
end

View File

@ -1,10 +1,10 @@
require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe Webrat::Logging do
it "should not log if there is no logger" do
klass = Class.new
klass.send(:include, Webrat::Logging)
klass.new.debug_log "Testing"
end
end
end

View File

@ -137,7 +137,7 @@ describe Webrat::Session do
webrat_session.redirect?.should be_false
end
end
describe "#internal_redirect?" do
before(:each) do
webrat_session = Webrat::Session.new
@ -149,19 +149,19 @@ describe Webrat::Session do
webrat_session.stub!(:response_location => "http://example.com")
webrat_session.internal_redirect?.should be_true
end
it "should return true if the last response was a redirect and the hosts are the same but the subdomains are different" do
webrat_session.stub!(:redirect? => true)
webrat_session.stub!(:current_url => "http://example.com")
webrat_session.stub!(:response_location => "http://myName.example.com")
webrat_session.internal_redirect?.should be_true
end
it "should return false if the last response was not a redirect" do
webrat_session.stub!(:redirect? => false)
webrat_session.internal_redirect?.should be_false
end
it "should return false if the last response was a redirect but the host of the current_url doesn't matches that of the response location" do
webrat_session.stub!(:redirect? => true)
webrat_session.stub!(:current_url => "http://example.com")
@ -176,23 +176,23 @@ describe Webrat::Session do
webrat_session.internal_redirect?.should be_false
end
end
describe "#redirected_to" do
before(:each) do
webrat_session = Webrat::Session.new
end
it "should return nil if not redirected" do
webrat_session.stub!(:redirect? => false)
webrat_session.redirected_to.should be_nil
end
it "should return the response_location if redirected" do
webrat_session.stub!(:redirect? => true)
webrat_session.stub!(:response_location => "http://www.example.com")
webrat_session.redirected_to.should == "http://www.example.com"
end
end
end
end

View File

@ -10,26 +10,26 @@ describe Webrat::MechanizeSession do
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)
@ -37,45 +37,45 @@ describe Webrat::MechanizeSession do
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
end

View File

@ -10,13 +10,13 @@ describe Webrat::MerbSession do
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
@ -30,13 +30,13 @@ describe Webrat::MerbSession do
@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
end

View File

@ -7,7 +7,7 @@ if defined?(Nokogiri::XML) && Webrat.configuration.parse_with_nokogiri?
def fail
raise_error(Spec::Expectations::ExpectationNotMetError)
end
before(:each) do
@text_and_password = <<-HTML
<div>
@ -16,29 +16,29 @@ if defined?(Nokogiri::XML) && Webrat.configuration.parse_with_nokogiri?
<span type="text"/>
</div>
HTML
@text_only = <<-HTML
<div>
<input type="text" disabled="disabled" />
</div>
HTML
@password_only = <<-HTML
<div>
<input type="password"/>
<div>
HTML
end
describe ":text" do
describe ":text" do
it "passes have_selector(:text) if a node with type=text exists" do
@text_and_password.should have_selector(":text")
end
it "passes not have_selector(:text) if no node with text=text exists" do
@password_only.should_not have_selector(":text")
end
it "fails have_selector(:text) if no node with type=text exists" do
lambda { @password_only.should have_selector(":text") }.should fail
end
@ -46,21 +46,21 @@ if defined?(Nokogiri::XML) && Webrat.configuration.parse_with_nokogiri?
it "fails not have_selector(:text) if a node with type=text exists" do
lambda { @text_only.should_not have_selector(":text") }.should fail
end
it "works together with other selectors" do
@text_and_password.should have_selector("input:text[type*='te']")
end
end
describe ":password" do
it "passes have_selector(:password) if a node with type=password exists" do
@text_and_password.should have_selector(":password")
end
it "passes not have_selector(:text) if no node with text=text exists" do
@text_only.should_not have_selector(":password")
end
it "fails have_selector(:password) if no node with type=password exists" do
lambda { @text_only.should have_selector(":password") }.should fail
end
@ -68,10 +68,10 @@ if defined?(Nokogiri::XML) && Webrat.configuration.parse_with_nokogiri?
it "fails not have_selector(:password) if a node with type=password exists" do
lambda { @password_only.should_not have_selector(":password") }.should fail
end
it "works together with other selectors" do
@text_and_password.should have_selector("input:password[type*='pa']")
end
end
end
end
end
end

View File

@ -78,4 +78,4 @@ describe "attach_file" do
attach_file "Picture", @filename, "image/png"
click_button
end
end
end

View File

@ -85,7 +85,7 @@ describe Webrat::RailsSession do
it "should provide a doc_root" do
Webrat::RailsSession.new(mock("integration session")).should respond_to(:doc_root)
end
it "should accept an ActiveRecord argument to #within and translate to a selector using dom_id" do
body = <<-HTML
<a href="/page1">Edit</a>
@ -93,18 +93,18 @@ describe Webrat::RailsSession do
<a href="/page2">Edit</a>
</div>
HTML
response = mock("response", :body => body, :headers => {}, :code => 200)
@integration_session.stub!(:response => response)
@integration_session.should_receive(:get).with("/page2", {}, nil)
rails_session = Webrat::RailsSession.new(@integration_session)
object = Object.new
object.stub!(:id => nil)
rails_session.within(object) do
rails_session.click_link 'Edit'
end
end
end
end

View File

@ -9,7 +9,7 @@ describe "Basic Auth HTTP headers" do
webrat_session.should_receive(:get).with("/", {}, {'HTTP_AUTHORIZATION' => "Basic dXNlcjpzZWNyZXQ=\n"})
visit("/")
end
it "should be present in form submits" do
with_html <<-HTML
<html>

View File

@ -20,10 +20,10 @@ describe "check" do
</form>
</html>
HTML
lambda { check "remember_me" }.should raise_error(Webrat::NotFoundError)
end
it "should check rails style checkboxes" do
with_html <<-HTML
<html>
@ -35,12 +35,12 @@ describe "check" do
</form>
</html>
HTML
webrat_session.should_receive(:get).with("/login", "user" => {"tos" => "1"})
check "TOS"
click_button
end
it "should result in the value on being posted if not specified" do
with_html <<-HTML
<html>
@ -50,12 +50,12 @@ describe "check" do
</form>
</html>
HTML
webrat_session.should_receive(:post).with("/login", "remember_me" => "on")
check "remember_me"
click_button
end
it "should fail if the checkbox is disabled" do
with_html <<-HTML
<html>
@ -65,10 +65,10 @@ describe "check" do
</form>
</html>
HTML
lambda { check "remember_me" }.should raise_error(Webrat::DisabledFieldError)
end
it "should result in a custom value being posted" do
with_html <<-HTML
<html>
@ -78,7 +78,7 @@ describe "check" do
</form>
</html>
HTML
webrat_session.should_receive(:post).with("/login", "remember_me" => "yes")
check "remember_me"
click_button
@ -105,10 +105,10 @@ describe "uncheck" do
</form>
</html>
HTML
lambda { uncheck "remember_me" }.should raise_error(Webrat::NotFoundError)
end
it "should fail if the checkbox is disabled" do
with_html <<-HTML
<html>
@ -120,7 +120,7 @@ describe "uncheck" do
HTML
lambda { uncheck "remember_me" }.should raise_error(Webrat::DisabledFieldError)
end
it "should uncheck rails style checkboxes" do
with_html <<-HTML
<html>
@ -151,7 +151,7 @@ describe "uncheck" do
uncheck "remember_me"
click_button
end
it "should work with checkboxes with the same name" do
with_html <<-HTML
<html>
@ -169,7 +169,7 @@ describe "uncheck" do
check 'Option 2'
click_button
end
it "should uncheck rails style checkboxes nested inside a label" do
with_html <<-HTML
<html>
@ -187,5 +187,5 @@ describe "uncheck" do
uncheck "TOS"
click_button
end
end

View File

@ -8,10 +8,10 @@ describe "choose" do
</form>
</html>
HTML
lambda { choose "first option" }.should raise_error(Webrat::NotFoundError)
end
it "should fail if input is not a radio button" do
with_html <<-HTML
<html>
@ -20,10 +20,10 @@ describe "choose" do
</form>
</html>
HTML
lambda { choose "first_option" }.should raise_error(Webrat::NotFoundError)
end
it "should check rails style radio buttons" do
with_html <<-HTML
<html>
@ -40,7 +40,7 @@ describe "choose" do
choose "Male"
click_button
end
it "should only submit last chosen value" do
with_html <<-HTML
<html>
@ -58,7 +58,7 @@ describe "choose" do
choose "Male"
click_button
end
it "should fail if the radio button is disabled" do
with_html <<-HTML
<html>
@ -68,10 +68,10 @@ describe "choose" do
</form>
</html>
HTML
lambda { choose "first_option" }.should raise_error(Webrat::DisabledFieldError)
end
it "should result in the value on being posted if not specified" do
with_html <<-HTML
<html>
@ -85,7 +85,7 @@ describe "choose" do
choose "first_option"
click_button
end
it "should result in the value on being posted if not specified and checked by default" do
with_html <<-HTML
<html>
@ -98,7 +98,7 @@ describe "choose" do
webrat_session.should_receive(:post).with("/login", "first_option" => "on")
click_button
end
it "should result in the value of the selected radio button being posted when a subsequent one is checked by default" do
with_html <<-HTML
<html>

View File

@ -425,7 +425,7 @@ describe "click_button" do
webrat_session.should_receive(:get).with("/login", "user" => {"email" => ""})
click_button
end
it "should recognize button tags" do
with_html <<-HTML
<html>
@ -448,9 +448,9 @@ describe "click_button" do
</html>
HTML
webrat_session.should_receive(:get)
click_button
click_button
end
it "should recognize image button tags" do
with_html <<-HTML
<html>

View File

@ -15,7 +15,7 @@ describe "fill_in" do
fill_in "User Text", :with => "filling text area"
click_button
end
it "should work with password fields" do
with_html <<-HTML
<html>
@ -37,10 +37,10 @@ describe "fill_in" do
</form>
</html>
HTML
lambda { fill_in "Email", :with => "foo@example.com" }.should raise_error(Webrat::NotFoundError)
end
it "should fail if input is disabled" do
with_html <<-HTML
<html>
@ -51,10 +51,10 @@ describe "fill_in" do
</form>
</html>
HTML
lambda { fill_in "Email", :with => "foo@example.com" }.should raise_error(Webrat::DisabledFieldError)
end
it "should allow overriding default form values" do
with_html <<-HTML
<html>
@ -69,7 +69,7 @@ describe "fill_in" do
fill_in "user[email]", :with => "foo@example.com"
click_button
end
it "should choose the shortest label match" do
with_html <<-HTML
<html>
@ -82,12 +82,12 @@ describe "fill_in" do
</form>
</html>
HTML
webrat_session.should_receive(:post).with("/login", "user" => {"mail1" => "", "mail2" => "value"})
fill_in "Some", :with => "value"
click_button
end
it "should choose the first label match if closest is a tie" do
with_html <<-HTML
<html>
@ -100,12 +100,12 @@ describe "fill_in" do
</form>
</html>
HTML
webrat_session.should_receive(:post).with("/login", "user" => {"mail1" => "value", "mail2" => ""})
fill_in "Some mail", :with => "value"
click_button
end
it "should anchor label matches to start of label" do
with_html <<-HTML
<html>
@ -115,10 +115,10 @@ describe "fill_in" do
</form>
</html>
HTML
lambda { fill_in "mail", :with => "value" }.should raise_error(Webrat::NotFoundError)
end
it "should anchor label matches to word boundaries" do
with_html <<-HTML
<html>
@ -128,10 +128,10 @@ describe "fill_in" do
</form>
</html>
HTML
lambda { fill_in "Email", :with => "value" }.should raise_error(Webrat::NotFoundError)
end
it "should work with inputs nested in labels" do
with_html <<-HTML
<html>
@ -148,7 +148,7 @@ describe "fill_in" do
fill_in "Email", :with => "foo@example.com"
click_button
end
it "should work with full input names" do
with_html <<-HTML
<html>
@ -176,7 +176,7 @@ describe "fill_in" do
fill_in "user[email]", :with => "foo@example.com"
click_button
end
it "should work with symbols" do
with_html <<-HTML
<html>
@ -191,7 +191,7 @@ describe "fill_in" do
fill_in :email, :with => "foo@example.com"
click_button
end
it "should escape field values" do
with_html <<-HTML
<html>

View File

@ -11,7 +11,7 @@ describe "field_by_xpath" do
</form>
</html>
HTML
field = field_by_xpath(".//input")
field.should_not be_nil
field.id.should == "element_42"

View File

@ -8,24 +8,24 @@ describe "field_labeled" do
with_html(html)
end
end
def field_labeled(label)
@label = label
yield
end
def should_return_a type, opts
it "should return a textfield" do
field_labeled(opts[:for]).should be_an_instance_of(type)
end
end
def with_an_id_of id, opts
it "should return an element with the correct id" do
field_labeled(opts[:for]).should match_id(id)
end
end
def should_raise_error_matching regexp, opts
it "should raise with wrong label" do
lambda {
@ -34,7 +34,7 @@ describe "field_labeled" do
end
end
end
def match_id(id)
simple_matcher "element with id #{id.inspect}" do |element, matcher|
if id.is_a?(Regexp)
@ -44,7 +44,7 @@ describe "field_labeled" do
end
end
end
describe "finding a text field" do
using_this_html <<-HTML
<html>
@ -54,12 +54,12 @@ describe "field_labeled" do
</form>
</html>
HTML
should_return_a Webrat::TextField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
should_raise_error_matching /Could not find .* "Other Label"/, :for => "Other Label"
end
describe "finding a hidden field" do
using_this_html <<-HTML
<html>
@ -69,12 +69,12 @@ describe "field_labeled" do
</form>
</html>
HTML
should_return_a Webrat::HiddenField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
should_raise_error_matching /Could not find .* "Other Label"/, :for => "Other Label"
end
describe "finding a checkbox" do
using_this_html <<-HTML
<html>
@ -84,12 +84,12 @@ describe "field_labeled" do
</form>
</html>
HTML
should_return_a Webrat::CheckboxField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
should_raise_error_matching /Could not find .* "Other Label"/, :for => "Other Label"
end
describe "finding a radio button" do
using_this_html <<-HTML
<html>
@ -99,13 +99,13 @@ describe "field_labeled" do
</form>
</html>
HTML
should_return_a Webrat::RadioField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
should_raise_error_matching /Could not find .* "Other Label"/, :for => "Other Label"
end
describe "finding a text area" do
using_this_html <<-HTML
<html>
@ -115,12 +115,12 @@ describe "field_labeled" do
</form>
</html>
HTML
should_return_a Webrat::TextareaField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
should_raise_error_matching /Could not find .* "Other Label"/, :for => "Other Label"
end
describe "finding a field with it's label containing newlines" do
using_this_html <<-HTML
<html>
@ -153,5 +153,5 @@ describe "field_labeled" do
should_return_a Webrat::TextField, :for => "The Label"
with_an_id_of "element_42", :for => "The Label"
end
end

View File

@ -10,7 +10,7 @@ describe "field_with_id" do
</form>
</html>
HTML
field_with_id("user's name").id.should == "user's name"
end
end

View File

@ -2,7 +2,7 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe "contain" do
include Webrat::Matchers
before(:each) do
@body = <<-HTML
<div id='main'>
@ -25,62 +25,62 @@ describe "contain" do
</div>
EOF
end
describe "#matches?" do
it "should call element#contains? when the argument is a string" do
@body.should contain("hello, world!")
end
it "should call element#matches? when the argument is a regular expression" do
@body.should contain(/hello, world/)
end
end
describe "asserts for contains," do
include Test::Unit::Assertions
before(:each) do
should_receive(:response_body).and_return @body
require 'test/unit'
end
describe "assert_contain" do
it "should pass when containing the text" do
assert_contain("hello, world")
end
it "should pass when containing the regexp" do
assert_contain(/hello, world/)
end
it "should throw an exception when the body doesnt contain the text" do
lambda {
assert_contain("monkeys")
}.should raise_error(Test::Unit::AssertionFailedError)
end
it "should throw an exception when the body doesnt contain the regexp" do
lambda {
assert_contain(/monkeys/)
}.should raise_error(Test::Unit::AssertionFailedError)
end
end
describe "assert_not_contain" do
it "should pass when not containing the text" do
assert_not_contain("monkeys")
end
it "should pass when not containing the regexp" do
assert_not_contain(/monkeys/)
end
it "should throw an exception when the body does contain the text" do
lambda {
assert_not_contain("hello, world")
}.should raise_error(Test::Unit::AssertionFailedError)
end
it "should throw an exception when the body does contain the regexp" do
lambda {
assert_not_contain(/hello, world/)
@ -93,21 +93,21 @@ describe "contain" do
it "should include the content string" do
hc = Webrat::Matchers::HasContent.new("hello, world!")
hc.matches?(@body)
hc.failure_message.should include("\"hello, world!\"")
end
it "should include the content regular expresson" do
hc = Webrat::Matchers::HasContent.new(/hello,\sworld!/)
hc.matches?(@body)
hc.failure_message.should include("/hello,\\sworld!/")
end
it "should include the element's inner content" do
hc = Webrat::Matchers::HasContent.new(/hello,\sworld!/)
hc.matches?(@body)
hc.failure_message.should include("hello, world!")
end
end

View File

@ -2,7 +2,7 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe "have_selector" do
include Webrat::Matchers
before(:each) do
@body = <<-HTML
<div id='main'>
@ -17,21 +17,21 @@ describe "have_selector" do
</div>
HTML
end
it "should be able to match a CSS selector" do
@body.should have_selector("div")
end
it "should not match a CSS selector that does not exist" do
@body.should_not have_selector("p")
end
describe "specifying attributes" do
it "should be able to specify the attributes of the tag" do
@body.should have_selector("div", :class => "inner")
end
end
describe "specifying content" do
it "should be able to specify the content of the tag" do
@body.should have_selector("div", :content => "hello, world!")
@ -49,7 +49,7 @@ describe "have_selector" do
@body.should have_selector("h4", :content => "Welcome 'Bryan\"")
end
end
describe "specifying counts" do
it "should be able to specify the number of occurences of the tag" do
@body.should have_selector("li", :count => 2)
@ -61,7 +61,7 @@ describe "have_selector" do
}.should raise_error(Spec::Expectations::ExpectationNotMetError)
end
end
describe "specifying nested elements" do
it "should be able to loop over all the matched elements" do
@body.should have_selector("div") do |node|
@ -90,7 +90,7 @@ describe "have_selector" do
end
}.should raise_error(Spec::Expectations::ExpectationNotMetError)
end
it "should work with items that have multiple child nodes" do
@body.should have_selector("ul") do |n|
n.should have_selector("li", :content => "First")
@ -98,32 +98,32 @@ describe "have_selector" do
end
end
end
describe "Test::Unit assertions" do
include Test::Unit::Assertions
before(:each) do
require 'test/unit'
should_receive(:response_body).and_return @body
end
describe "assert_have_selector" do
it "should pass when body contains the selection" do
assert_have_selector("div")
end
it "should throw an exception when the body doesnt have matching selection" do
lambda {
assert_have_selector("p")
}.should raise_error(Test::Unit::AssertionFailedError)
end
end
describe "assert_have_not_selector" do
it "should pass when the body doesn't contan the selection" do
assert_have_no_selector("p")
end
it "should throw an exception when the body does contain the selection" do
lambda {
assert_have_no_selector("div")
@ -131,5 +131,5 @@ describe "have_selector" do
end
end
end
end

View File

@ -3,7 +3,7 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe "have_tag" do
include Webrat::Matchers
include Webrat::HaveTagMatcher
before(:each) do
@body = <<-HTML
<div id='main'>
@ -15,21 +15,21 @@ describe "have_tag" do
it "should be an alias for have_selector" do
@body.should have_tag("div")
end
describe "asserts for tags" do
include Test::Unit::Assertions
before(:each) do
should_receive(:response_body).and_return @body
require 'test/unit'
end
describe "assert_have_tag" do
it "should be an alias for assert_have_selector" do
assert_have_tag("div")
end
end
describe "assert_have_no_tag" do
it "should be an alias for assert_have_no_selector" do
assert_have_no_tag("p")

View File

@ -2,7 +2,7 @@ require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe "have_xpath" do
include Webrat::Matchers
before(:each) do
@body = <<-HTML
<div id='main'>
@ -17,49 +17,49 @@ describe "have_xpath" do
</div>
HTML
end
it "should be able to match an XPATH" do
@body.should have_xpath("//div")
end
it "should be able to match an XPATH with attributes" do
@body.should have_xpath("//div", :class => "inner")
end
it "should be able to match an XPATH with content" do
@body.should have_xpath("//div", :content => "hello, world!")
end
it "should not match an XPATH without content" do
@body.should_not have_xpath("//div", :content => "not present")
end
it "should be able to match an XPATH with content and class" do
@body.should have_xpath("//div", :class => "inner", :content => "hello, world!")
end
it "should not match an XPATH with content and wrong class" do
@body.should_not have_xpath("//div", :class => "outer", :content => "hello, world!")
end
it "should not match an XPATH with wrong content and class" do
@body.should_not have_xpath("//div", :class => "inner", :content => "wrong")
end
it "should not match an XPATH with wrong content and wrong class" do
@body.should_not have_xpath("//div", :class => "outer", :content => "wrong")
end
it "should not match a XPATH that does not exist" do
@body.should_not have_xpath("//p")
end
it "should be able to loop over all the matched elements" do
@body.should have_xpath("//div") do |node|
node.first.name.should == "div"
end
end
it "should not match if any of the matchers in the block fail" do
lambda {
@body.should have_xpath("//div") do |node|
@ -67,19 +67,19 @@ describe "have_xpath" do
end
}.should raise_error(Spec::Expectations::ExpectationNotMetError)
end
it "should be able to use #have_xpath in the block" do
@body.should have_xpath("//div[@id='main']") do |node|
node.should have_xpath("./div[@class='inner']")
end
end
it "should convert absolute paths to relative in the block" do
@body.should have_xpath("//div[@id='main']") do |node|
node.should have_xpath("//div[@class='inner']")
end
end
it "should not match any parent tags in the block" do
lambda {
@body.should have_xpath("//div[@class='inner']") do |node|
@ -87,15 +87,15 @@ describe "have_xpath" do
end
}.should raise_error(Spec::Expectations::ExpectationNotMetError)
end
describe 'asserts for xpath' do
include Test::Unit::Assertions
before(:each) do
should_receive(:response_body).and_return @body
require 'test/unit'
end
describe "assert_have_xpath" do
it "should pass when body contains the selection" do
assert_have_xpath("//div")

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