Пытаясь загрузить файл yaml, перебрать хеш и выполнить некоторую логику

Пытаясь загрузить файл yaml, переберите хеш и выполните некоторую логику. Я использую Watir-Webdriver/Ruby для ответа на случайно выбранные вопросы, вопросы / ответы известны и хранятся в файле YAML (kba.yml).

Я использую Ruby/Page Objects/YAML файл /Watir-Webdriver.

Мой файл YAML (kba.yml):

1:
  question: "Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'."
  answer: "Google"

2:  
  question: "According to our records, you graduated from which of the following High Schools?"
  answer: "NONE OF THE ABOVE/DOES NOT APPLY"

3:  
  question: "I was born within a year or on the year of the date below."
  answer_1: "1942"
  answer_2: "1941"
  answer_3: "1943"

Где я загружаю свой файл YAML (внутри моего env.rb):

require 'yaml'
KBA = YAML.load_file('config/data/kba.yml')

Мой код для перебора хеша из файла yaml и выполнения некоторой логики:

Цикл первого случайного вопроса:

KBA.each do |key, value| 
  value.each do |question, answer|
    puts "blah question: #{question}"
      if (@browser.h2s[0].text.sub (/^\d.\s/), '') == question
        puts "Question matched and selected: #{question}"
        case answer
        when @browser.labels[0].text
          select_first_q_first_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[1].text
          select_first_q_second_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[2].text
          select_first_q_third_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[3].text
          select_first_q_fourth_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[4].text
          select_first_q_fifth_radio 
          puts "Answer matched and selected #{answer}"
        else 
          puts "The answer is not present for this question!"
        end
      else
        puts "This question is not stored in the dataset: #{@browser.h2s[0].text}"
      end
    end
end

Цикл для второго случайного вопроса:

KBA.each do |question, answer| 
    if (@browser.h2s[1].text.sub (/^\d.\s/), '') == question
      puts "Question matched and selected: #{question}"
      case answer
      when @browser.labels[0].text
        select_second_q_first_radio
        puts "Answer matched and selected #{answer}"
      when @browser.labels[1].text
        select_second_q_second_radio
        puts "Answer matched and selected #{answer}"
      when @browser.labels[2].text
        select_second_q_third_radio
        puts "Answer matched and selected #{answer}"
      when @browser.labels[3].text
        select_second_q_fourth_radio
        puts "Answer matched and selected #{answer}"
      when @browser.labels[4].text
        select_second_q_fifth_radio 
        puts "Answer matched and selected #{answer}"
      else 
        puts "The answer is not present for this question!"
      end
    else
      puts "This question is not stored in the dataset: #{@browser.h2s[1].text}"
    end  
  end

Цикл третьего случайного вопроса:

  KBA.each do |question, answer| 
      if (@browser.h2s[2].text.sub (/^\d.\s/), '') == question
        puts "Question matched and selected: #{question}"
        case answer
        when @browser.labels[0].text
          select_third_q_first_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[1].text
          select_third_q_second_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[2].text
          select_third_q_third_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[3].text
          select_third_q_fourth_radio
          puts "Answer matched and selected #{answer}"
        when @browser.labels[4].text
          select_third_q_fifth_radio 
          puts "Answer matched and selected #{answer}"
        else 
          puts "The answer is not present for this question!"
        end
      else
        puts "This question is not stored in the dataset: #{@browser.h2s[2].text}"
      end 
    end
end

Судя по выводу, мой код фактически не проверяет правильность значения вопроса и ответа, как бы я это сделал?

Это вывод:

blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: question
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer_1
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer_2
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
blah question: answer_3
This question is not stored in the dataset: 1. Which of the following is a current or previous employer? If there is not a matched employer name, please select 'NONE OF THE ABOVE'.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 2. I was born within a year or on the year of the date below.
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?
This question is not stored in the dataset: 3. Which of the following represents the last four digits of your primary checking account number?

ОБНОВЛЕНИЕ: Объект страницы с 3 вопросами:

class LOA2KBAQuestions

  include PageObject
  include ErrorMessages
  include DataMagic

  h2(:question, :class => "question")

  #radio buttons for the answers for the first question
  radio_button(:first_q_first_radio, :id => "answers_question_0_1")
  radio_button(:first_q_second_radio, :id => "answers_question_0_2")
  radio_button(:first_q_third_radio, :id => "answers_question_0_3")
  radio_button(:first_q_fourth_radio, :id => "answers_question_0_4")
  radio_button(:first_q_fifth_radio, :id => "answers_question_0_5")

  #radio buttons for the answers for the second question
  radio_button(:second_q_first_radio, :id => "answers_question_1_1")
  radio_button(:second_q_second_radio, :id => "answers_question_1_2")
  radio_button(:second_q_third_radio, :id => "answers_question_1_3")
  radio_button(:second_q_fourth_radio, :id => "answers_question_1_4")
  radio_button(:second_q_fifth_radio, :id => "answers_question_1_5")

  #radio buttons for the answers for the third question
  radio_button(:third_q_first_radio, :id => "answers_question_2_1")
  radio_button(:third_q_second_radio, :id => "answers_question_2_2")
  radio_button(:third_q_third_radio, :id => "answers_question_2_3")
  radio_button(:third_q_fourth_radio, :id => "answers_question_2_4")
  radio_button(:third_q_fifth_radio, :id => "answers_question_2_5")

  button(:submit, :text => "Submit Answers")
end

Также я получаю доступ к реальным вопросам, таким как этот (они все в тегах h2, я использую регулярное выражение для удаления # перед вопросом. И я получаю доступ к вопросу, добавляя [x] после тега h2):

@browser.h2s[0].text.sub (/^\d.\s/), ''

Поэтому я не стал использовать объявленный объект страницы для тега h2, так как не знал, как его использовать для доступа к трем вопросам.

ОБНОВЛЕНИЕ - Пример HTML страницы на 3 вопроса:

  <div class="question">

    <h2>


        1.
        Which of the following is a current or previou…

    </h2>
    <div class="answers">
        <p>
            <label>
                <input id="answers_question_0_1" type="radio" value="1" name="answers[question_0]" checked="checked"></input>


                RITEWAY

            </label>
        </p>
        <p>
            <label>
                <input id="answers_question_0_2" type="radio" value="2" name="answers[question_0]"></input>


                NEW ALTERNATIVES

            </label>
        </p>
        <p></p>
        <p></p>
        <p></p>
    </div>

</div>
<div class="question">

    <h2>


        2.
        I was born within a year or on the year of the…

    </h2>
    <div class="answers">
        <p>
            <label>
                <input id="answers_question_1_1" type="radio" value="1" name="answers[question_1]" checked="checked"></input>


                1936

            </label>
        </p>
        <p>
            <label>
                <input id="answers_question_1_2" type="radio" value="2" name="answers[question_1]"></input>


                1939

            </label>
        </p>
        <p>
            <label>
                <input id="answers_question_1_3" type="radio" value="3" name="answers[question_1]"></input>


                1942

            </label>
        </p>
        <p></p>
        <p></p>
    </div>

</div>

1 ответ

Решение

Проблема в том, как зацикливался файл YAML. Например, в:

KBA.each do |key, value|
  value.each do |question, answer|
  end
end

value это хеш, так что question а также answer не будет ожидаемых значений. На самом деле они будут парами ключ / значение. Это должно было быть:

KBA.each do |key, value|
  question = value['question']
  answer = value['answer']
end

Вместо того, чтобы пытаться разобраться в каждом вопросе / ответе в файле YAML, я бы посмотрел конкретный вопрос и ответы. На следующем объекте страницы answer_questions будут:

  1. Определите, что вопрос основан на элементе h2.
  2. Посмотрите на файлы YAML, чтобы найти все правильные ответы на вопрос.
  3. Найдите и выберите переключатель, который соответствует одному из действительных ответов.

Пример объекта страницы:

class MyPage
  include PageObject

  divs(:question, :class => 'question')

  def answer_questions
    question_elements.each do |question|
      # Determine what the question is
      question_text = question.h2_element.text.sub(/^\d.\s/, '')

      # Get the valid answers for the question
      question_data = KBA.find { |_, value| value['question'] == question_text }
      unless question_data
        puts "Question not found: #{question_text}"
        next
      end
      valid_answers = question_data[1].select { |k, _| k =~ /answer/ }.values

      # Set the radio buttons if they match one of the answers
      answer = question.radio_button_elements.find do |radio|
        label = radio.parent.text
        valid_answers.include?(label)
      end
      unless answer
        puts "Unable to answer question: #{question_text}"
        next
      end
      answer.select
    end
  end
end
Другие вопросы по тегам