Define a #dom method on response objects after parsing them with nokogiri

This commit is contained in:
Bryan Helmkamp 2008-11-06 23:08:46 -05:00
parent ee3f70edf4
commit b23dcfb213
5 changed files with 41 additions and 17 deletions

View File

@ -1,6 +1,7 @@
require "nokogiri"
require "webrat/core/form"
require "webrat/core/locators"
require "webrat/core_extensions/meta_class"
module Webrat
class Scope
@ -8,10 +9,11 @@ module Webrat
include Flunk
include Locators
def initialize(session, html, selector = nil)
@session = session
@html = html
@selector = selector
def initialize(session, response, response_body, selector = nil)
@session = session
@response = response
@response_body = response_body
@selector = selector
end
# Verifies an input field or textarea exists on the current page, and stores a value for
@ -139,7 +141,25 @@ module Webrat
alias_method :clicks_button, :click_button
def dom # :nodoc:
@dom ||= Nokogiri::HTML(scoped_html)
return @dom if @dom
if @response.respond_to?(:dom)
page_dom = @response.dom
else
page_dom = Nokogiri::HTML(@response_body)
@response.meta_class.send(:define_method, :dom) do
page_dom
end
end
if @selector
@dom = Nokogiri::HTML(page_dom.search(@selector).first.to_html)
else
@dom = page_dom
end
return @dom
end
protected
@ -152,16 +172,6 @@ module Webrat
end
end
def scoped_html
@scoped_html ||= begin
if @selector
(Nokogiri::HTML(@html) / @selector).first.to_html
else
@html
end
end
end
def areas
(dom / "area").map do |element|
Area.new(@session, element)

View File

@ -133,7 +133,7 @@ module Webrat
alias_method :clicks_link_within, :click_link_within
def within(selector)
scopes.push(Scope.new(self, response_body, selector))
scopes.push(Scope.new(self, response, response_body, selector))
ret = yield(current_scope)
scopes.pop
return ret
@ -169,7 +169,7 @@ module Webrat
end
def page_scope
@_page_scope ||= Scope.new(self, response_body)
@_page_scope ||= Scope.new(self, response, response_body)
end
def_delegators :current_scope, :fill_in, :fills_in

View File

@ -0,0 +1,6 @@
class ::Object
def meta_class
class << self; self end
end
end

View File

@ -7,6 +7,10 @@ module Webrat
File.expand_path(File.join(".", "public"))
end
def response
@response ||= Object.new
end
def response_code
@response_code || 200
end

View File

@ -10,6 +10,10 @@ describe Webrat::Session do
it "should expose the current_dom" do
session = Webrat::Session.new
def session.response
Object.new
end
def session.response_body
"<html></html>"
end