【问题标题】:Finding the text of a label using Capybara使用 Capybara 查找标签的文本
【发布时间】:2016-03-09 20:47:01
【问题描述】:

使用 Capybara 查找标签的文本

背景:我有一个 KBA 页面和一组问题和答案,答案是使用单选按钮的 5 个可能答案的形式。所以我需要循环遍历每个单选按钮的每个标签,以匹配 yaml 文件中的有效答案。

HTML:

<div class="questions"></div>
<div class="answers"></div>
  <p>
    <label>
     <input id="answers_question_0_1" type="radio" checked="checked" value="1" name="answers[question_0]"></input>
     RADIO BUTTON TEXT 1
    </label>
  </p>
  <p></p> #another radio button and label text 2
  <p></p> #another radio button and label text 3
  <p></p> #another radio button and label text 4
  <p></p> #another radio button and label text 5

我的测试代码:

  def answer_questions

   .
   .
   . 

   i=0

   def answers
     page.all('.answers')
   end

   #This is accessing the answer value from the selected correct question from the kba.yml file
   valid_answers = this variable contains the valid answer to the question

   #********THIS IS THE PROBLEM BLOCK*****************************
   #Set the radio buttons if they match one of the answers
   @correct_answer = answers[i].all(:radio_button).find do |radio|
     valid_answers.include?(radio.parent.text)
   end
   #********THIS IS THE PROBLEM BLOCK*****************************      

   i +=1

   unless @correct_answer
     p "Unable to answer question: #{question_text}" and next
   end

   @correct_answer.select

  end

问题出在上面代码sn-p中提到的“问题块”。我不知道如何获取与每个单选按钮一个标签/p 标签相关联的文本,而是返回所有单选按钮的文本并对照变量“valid_answers”进行检查,但总是失败。

我基本上希望radio.button.text 等于“RADIO BUTTON TEXT 1”,因为它是相应的单选按钮。但是radio.button.text 却返回:

单选按钮文本 1 单选按钮文本 2 单选按钮文本 3 等

我猜它不应该是radio.parent.text,而是别的东西,我不确定。

【问题讨论】:

    标签: ruby selenium-webdriver capybara


    【解决方案1】:

    看起来你让事情变得比它需要的更复杂 - 你应该能够做到

    answers[i].choose("the text of the radio button you want to select")
    

    如果未找到该值,您可以捕获异常并在此处输出警告。

    注意:Capybara 元素中的父元素不是该元素的 HTML 父元素 - 它是查找给定元素时调用的元素 - 所以在你的情况下它是 .answers 元素。如果您确实想访问节点的实际 HTML 父元素,您可以调用 element.find(:xpath, '..')

    【讨论】:

    • 汤姆,谢谢,你带我走上正确的道路,只是稍微改变了你所说的:answers[i].choose(valid_answer[0])
    猜你喜欢
    • 2012-04-22
    • 2020-04-21
    • 2019-01-22
    • 2011-07-22
    • 2011-02-24
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多