diff --git a/lib/webrat/core/scope.rb b/lib/webrat/core/scope.rb index 2207d4b..366289b 100644 --- a/lib/webrat/core/scope.rb +++ b/lib/webrat/core/scope.rb @@ -9,11 +9,23 @@ module Webrat include Flunk include Locators - def initialize(session, response, response_body, selector = nil) - @session = session - @response = response - @response_body = response_body - @selector = selector + def self.from_page(session, response, response_body) + new(session) do + @response = response + @response_body = response_body + end + end + + def self.from_scope(session, scope, selector) + new(session) do + @scope = scope + @selector = selector + end + end + + def initialize(session, &block) + @session = session + instance_eval(&block) if block_given? end # Verifies an input field or textarea exists on the current page, and stores a value for @@ -143,18 +155,8 @@ module Webrat def dom # :nodoc: 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) + @dom = scoped_dom else @dom = page_dom end @@ -164,6 +166,22 @@ module Webrat protected + def page_dom + return @response.dom if @response.respond_to?(:dom) + + dom = Nokogiri::HTML(@response_body) + + @response.meta_class.send(:define_method, :dom) do + dom + end + + return dom + end + + def scoped_dom + Nokogiri::HTML(@scope.dom.search(@selector).first.to_html) + end + def locate_field(field_locator, *field_types) if field_locator.is_a?(Field) field_locator diff --git a/lib/webrat/core/session.rb b/lib/webrat/core/session.rb index b175bcf..ff0ae22 100644 --- a/lib/webrat/core/session.rb +++ b/lib/webrat/core/session.rb @@ -133,7 +133,7 @@ module Webrat alias_method :clicks_link_within, :click_link_within def within(selector) - scopes.push(Scope.new(self, response, response_body, selector)) + scopes.push(Scope.from_scope(self, current_scope, 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, response_body) + @_page_scope ||= Scope.from_page(self, response, response_body) end def_delegators :current_scope, :fill_in, :fills_in diff --git a/spec/api/within_spec.rb b/spec/api/within_spec.rb index d9db9dc..c093f4b 100644 --- a/spec/api/within_spec.rb +++ b/spec/api/within_spec.rb @@ -5,6 +5,24 @@ describe "within" do @session = Webrat::TestSession.new end + it "should work when nested" do + @session.response_body = <<-EOS +