Zack
Zack

Reputation: 2497

Getting text all all links on a page.

I am writing a test where I want to get all the options that are displayed in a menu. The HTML for the menu is as follows:

<div class="dropdown-menu context-menu open" style="display: block; left: 421px; top: 352px;">
    <li>
        <a href="#" onclick="save;">Save</a>
    </li>
    <li>
        <a href="#" onclick="duplicate;">Duplicate</a>
    </li>
    <li>
        <a href="#" onclick="delete;">Delete</a>
    </li>
</div>

I m using page objects with Capybara to do my testing. Currently, I have this...

module PageObjects
  module SomePage
    class OtherPage < PageObject
      def menu_options
        @element.right_click
        options = @page.all('div.dropdown-menu li')
        menu_options = options.map{ |option| MenuOption.new(option)}
        return menu_options.map{|m| m.text}
      end
    end

    class MenuOption < PageObject
      def text
        @element.find('a').text
      end
    end
  end
end

This allows me to, in my test, call other_page.menu and get ["Save","Duplicate","Delete"]. What I am hoping to do is get rid of the MenuOption class. Is there someway to write the menu_options method such that it will get the text from all the elements?

Upvotes: 0

Views: 342

Answers (1)

Justin Ko
Justin Ko

Reputation: 46836

You could have the menu_options method:

  1. Get all of the links instead of the list items.
  2. Map the text of each element directly rather than mapping them to a MenuOption.

The method would be:

def menu_options
  @element.right_click
  options = @page.all('div.dropdown-menu li a')
  options.map{ |option| option.text }
end

Upvotes: 1

Related Questions