Search code examples
rubyrspecautomated-testscapybara

Capybara / Ruby - Trying to get only the Text from all ambiguous css selector and convert it to string


I'm trying to get all Texts from a specific CSS Selector that are ambiguous in the HTML. I would like to access these ambiguous css and get the Text and then return all that info.

I've figured out how to find all ambiguous selectors but I dont know how to get just the text from each selector.

The ambiguous selector is (it finds 3 matchers) .list-card-title .js-card-name

I've already tried commands like:

arr = Array(3) arr = find_all('.list-card-title.js-card-name').to_a puts arr.to_s

When I use puts arr

I got the following output [#<Capybara::Node::Element tag="span" path="/HTML/BODY[1]/DIV[2]/DIV[2]/DIV[1]/DIV[2]/DIV[3]/DIV[1]/DIV[1]/DIV[3]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/A[1]/DIV[3]/SPAN[1]">, #<Capybara::Node::Element tag="span" path="/HTML/BODY[1]/DIV[2]/DIV[2]/DIV[1]/DIV[2]/DIV[3]/DIV[1]/DIV[1]/DIV[3]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/A[2]/DIV[3]/SPAN[1]">, #<Capybara::Node::Element tag="span" path="/HTML/BODY[1]/DIV[2]/DIV[2]/DIV[1]/DIV[2]/DIV[3]/DIV[1]/DIV[1]/DIV[3]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/A[3]/DIV[3]/SPAN[1]">]


Solution

  • To get the text of elements you need to call text on each of the elements. In your case the easiest way to do that would be

    find_all('.list-card-title.js-card-name').map(&:text)
    

    which will return an array of the text contained in each of the elements. If you then want all of that concatenated into one string you could do

    find_all('.list-card-title.js-card-name').map(&:text).join
    

    Note: you have tagged your questions with automated-tests, are you actually testing an app/site, or are you instead doing web scraping? If you are testing you'd be much better off writing your tests using Capybaras expectation/assertion methods (and the :text options they accept) rather than finding elements, extracting/manipulating contained text and then doing something (I assume asserting on) with that.