Search code examples
rubycucumbercapybarasite-prism

Can we navigate to different pages inside within loop in capybara/siteprism?


My code is like this:

my_array.each do |element|
  within element do
    some_element.click         #it will take me to next page
    some_other_element.click   #it will take me to previous page for next iteration
  end
end

In siteprism page it is like this:

elements :array, 'ul.class li'

When I run, its executing successfully for the first iteration, but in second iteration its throwing error like cache element not available

If I navigate to different pages then i loose the scope of my_array elements??

Can anyone help me with this...??


Solution

  • If I navigate to different pages then i loose the scope of array elements??

    Yes, the scope has changed.

    The reason it fails is because the elements that are on the page when the loop first runs are not present on the second page even though it may look like they are - they are different elements. Because you have moved page you need to get the elements again from scratch.

    On how to make it work...

    There seem to be a number of issues with the code in the question. The first is that the fact you are using a within block in the context of an element instead of a section. The first thing I'd do (not being able to see your code) is to replace your elements with sections, and I'd model whatever the li is as a section. Eg:

    class MySection < SitePrism::Section
      element :some_element, "#some-element"
      element :some_other_element, "#some_other_element"
    end
    

    Then I'd add model the li elements of the ul as a collection of sections in a page, eg:

    class MyPage < SitePrism::Page
      sections :list_items, MySection, 'ul.class li'
    end
    

    To get around the scoping issue, I'd have something like the following:

    @my_page = MyPage.new
    
    number_of_list_items = @my_page.list_items.size
    
    number_of_list_items.times do |list_item_position|
      MyPage.new.list_items[list_item_position].some_element.click
      MyPage.new.list_items[list_item_position].some_other_element.click
    end