I Durrani
I Durrani

Reputation: 91

Using capybara to select a bootstrap radio button

I have a set of radio buttons using bootstrap and want to use Capybara to select them using either id or value. For my rspec tests. For some reason it's not seeing the radio buttons and I wonder if anyone can have a look and suggest something.

Error I'm getting is

Capybara::ElementNotFound: Unable to find visible radio button "paper" that is not disabled Capybara::ElementNotFound: Unable to find visible radio button "#paper" that is not disabled

HTML`

        </label>
        <label for="paper" id="paper" class="btn btn-primary choice col-lg-4 col-md-4">
          <input type="radio" value = "paper" name="rps" id="paper">
          <img class="card-img-top img-fluid image-responsive" src="/img/paper.png" alt="Paper">
          </input>

        </label>
        <label for="scissors" class="btn btn-primary choice col-lg-4 col-md-4">
          <input type="radio" value = "scissors" name="rps" id="scissors">
          <img class="card-img-top img-fluid image-responsive" src="/img/scissors.png" alt="Scissors">
          </input>

        </label>
      </div>`

TEST

 feature 'Testing if we divert to /result chosing an option and play' do
  scenario 'Choose option and click play' do
    sign_in_and_play
    click_button('Play')
    choose("#paper")
    # choose("paper")
    expect(page).to have_content("Result displayed here")
  end
end

Any help would be much appreciated. Thanks

Upvotes: 3

Views: 1372

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49870

Capybara is telling you it can't find the radio buttons because they aren't actually visible on the page. Most likely, if you inspect the page you'll see that bootstrap is hiding the actual radio buttons (probably with visibility: hidden CSS) and replacing them with images so the styling is consistent across browsers. One solution to this is to allow Capybara to click on the label rather than needing to click specifically on the radio button:

choose('scissors', allow_label_click: true)

You can also default to allowing label clicks by setting Capybara.automatic_label_click = true

Note: your sample HTML is illegal since both the paper label and input have id="paper" - I'm assuming that is meant to be like the "scissors" option where the id is only on the input.

Upvotes: 7

Related Questions