How to check a checkbox in capybara?

前端 未结 13 1853
灰色年华
灰色年华 2020-11-30 23:34

I\'m using Rspec and Capybara.

How can I write a step to check a checkbox? I\'ve tried check by value but it can\'t find my checkbox<

相关标签:
13条回答
  • 2020-11-30 23:44

    to select the checkbox

      check 'name_of_checkbox'
    
    0 讨论(0)
  • 2020-11-30 23:48

    I found the following worked for me:

    # Check
    find(:css, "#cityID[value='62']").set(true)
    
    # Uncheck
    find(:css, "#cityID[value='62']").set(false)
    
    0 讨论(0)
  • When running capybara test, you got the page object. This you can use to check/uncheck any checkboxes. As @buruzaemon already mentioned:

    to find and check a checkbox by name, id, or label text.

    So lets assume you got a checkbox in your html like:

    <label>  
      <input type="checkbox" value="myvalue" name="myname" id="myid">
      MyLabel
    </label>
    

    You could check this with:

    page.check('myid')
    page.check('MyLabel')
    page.check('myname')
    

    Uncheck is the same just use page.uncheck method.

    0 讨论(0)
  • 2020-11-30 23:50

    It's better not to create multiple elements with the same id, so that (and not only for that) you can easily check/uncheck a checkbox with elegant

    check 'cityID'
    uncheck 'cityID'
    

    If one can not avoid multiple elements with the same id and still needs to check a checkbox with certain value, he can do so with

    find(:css, "#cityID[value='62']").set(true)
    find(:css, "#cityID[value='62']").set(false)
    

    More information on capybara input manipulations can be found here

    0 讨论(0)
  • 2020-11-30 23:52

    An old topic but another solution is:

    check('Option 3', allow_label_click: true)

    0 讨论(0)
  • 2020-11-30 23:52

    Had some issues with custom checkbox which is hidden behind label element. Needed a allow_label_click: true.

    With reference to this blog post,

    check 'checkbox[name]', allow_label_click: true
    

    For cases where there is a link in your label like "I agree to terms and conditions", the above code will open the page, which is not what you want.

    Do this instead.

    find(:css, "#checkbox_id", visible: false).execute_script('this.checked = true')
    
    0 讨论(0)
提交回复
热议问题