开发者

Cucumber + Capybara + Selenium: selecting text

I'm making changes to a text editor, and I need to be ab开发者_StackOverflowle to select text to manipulate it with JavaScript. How do I select text with Cucumber, Capybara and Selenium?


I found another stackoverflow question that talks about how to select text using JavaScript.

Can you set and/or change the user’s text selection in JavaScript?

I was able to modify their script to be able to work within a getEval call from Selenium IDE (if you're using Selenium in a different way, you may need to modify it). I also stripped out the code not pertinent to Firefox:

function selectElementContents(el,start,end) {
    var sel = window.getSelection();
    var range = window.document.createRange();
    range.setStart(el,start);
    range.setEnd(el,end);
    sel.removeAllRanges();
    sel.addRange(range);
}
selectElementContents(window.document.getElementById("container").firstChild,10,20)

This allows you to select a range of text within a single element. "Container" is the ID of the element containing the text, and 10 and 20 are the indexes of characters to start and stop at.

Just condense this down to one line, add it to a Selenium getEval statement, and it should select the text for you.

If text within a single element isn't flexible enough for you, documentation on JavaScript ranges should provide you the extra detail you need.


Tying the approach suggested by Josh into a Capybara helper function (and adding optional position arguments for partial selections within the start/end elements):

module TextSelection
  def select_text(startEl, endEl, startPos = 0, endPos = 0)
    js = <<-JS
      var sel = window.getSelection();
      var range = window.document.createRange();
      range.setStart(arguments[0],#{startPos});
      range.setEnd(arguments[1],#{endPos});
      sel.removeAllRanges();
      sel.addRange(range);
    JS

    page.execute_script(js, startEl.native, endEl.native)
  end
end

World(TextSelection)

Then, in your test:

start_el = first('#first')
end_el = first('#last')
select_text(start_el, end_el)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜