Capybara在RSpec测试中无法匹配Bootstrap单选按钮问题排查
The problem boils down to how Bootstrap styles custom radio buttons and how Capybara's have_checked_field matcher works by default.
Bootstrap's custom-control-input class hides the actual <input> element (using CSS like position: absolute or opacity: 0) while styling the associated <label> to look like the radio button. Even though the label is visible to users, the underlying input element is technically hidden.
Capybara's have_checked_field matcher defaults to only looking for visible form fields. When you run:
expect(page).to have_checked_field('Hidden')
Capybara finds the "Hidden" label, locates the associated hidden input, but then rejects it because it's not visible—hence the error message about not finding a visible field.
The Fix
Modify your expectation to include the visible: false option, which tells Capybara to include hidden elements in its search:
expect(page).to have_checked_field('Hidden', visible: false)
This will correctly find the hidden radio input that's checked, which is associated with the "Hidden" label, without relying on fragile CSS or XPath selectors.
Why This Works
- The
visible: falseflag overrides Capybara's default behavior of only checking visible elements. - Using the label text ("Hidden") keeps your test focused on user-facing content, which aligns with your goal of avoiding brittle selectors.
内容的提问来源于stack exchange,提问作者John Y

