Capybara: Select an option by value not text

前端 未结 8 493
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 16:10

For the HTML


                        
    
提交评论

  • 2020-12-23 16:34

    That helper method is pretty clever. I would change it just a little bit:

    def select_by_value(id, value)
    
      option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
    
      find(:xpath, option_xpath).click
    
    end
    

    or just:

    find(:xpath, "//select[@id='date']/option[@value='20120904']").click
    
    0 讨论(0)
  • 2020-12-23 16:36

    In my case I have a few options with same text, that's the reason why I need select by value. Combining a few answers together I've found the best solution for me:

    def select_by_value(id, value)
      option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
      find(:xpath, option_xpath).select_option
    end
    
    0 讨论(0)
  • 2020-12-23 16:37

    You can also achieve it by doing the following:

    find_by_id('date').find("option[value='20120905']").click
    
    0 讨论(0)
  • 2020-12-23 16:43

    I wrote a helper method:

    def select_by_value(id, value)
      option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
      option = find(:xpath, option_xpath).text
      select(option, :from => id)
    end
    

    Save in a .rb file in spec/support/

    Example use:

    before do
      select_by_value 'some_field_id', 'value'
      click_button 'Submit'
    end
    
    0 讨论(0)
  • 2020-12-23 16:45

    This will work to select an option by value:

    find("option[value='20120905']").click
    

    To maintain the scope of the selector you could wrap it in a within block as such:

    within '#date' do
      find("option[value='20120905']").click
    end
    
    0 讨论(0)
  • 提交回复
    热议问题