Home > other >  How to click a span in capybara tests?
How to click a span in capybara tests?

Time:06-11

I'm trying to click on a checkbox, but when I run the action, it doesn't work. I'm using the same way to click buttons and other elements. I'm using a data-testid to find the checkbox in the view. I need to click on the checkbox, and after clicking execute the actions of the next step. This checkbox is a react component that will have a span in the view.

 context 'when the user agrees to charges by clicking a checkbox' do

          before do
            # sleep 1000
            wait_before_clicking
            page.find("span[data-testid='prepay-enrollment-modal-agreement-checkbox']").click
          end
          
          it 'renders new content for the user to review payment details' do
            expect(page).to have_selector("[data-testid='review-step-container']")
            expect(page).to have_content("Your Plan")
            expect(page).to have_content("100 pages/ month")
            expect(page).to have_content("Plan cost for 12 months, before discount")
            expect(page).to have_content("Prepay discount (10%)")
            expect(page).to have_content("Total Due:")
          end
        end

enter image description here

CodePudding user response:

The data-testid attribute is on the input element not on the span, so find("span[data-testid='prepay-enrollment-modal-agreement-checkbox']") won't work. If you put the data-testid attribute on the span rather than the input then it would work, however there's a better way. Since the checkbox has an associated label element you can just tell Capybara it's allowed to click on the label element if necessary. First, since you're using test ids, set

Capybara.test_id = 'data-testid'

in your global config, and then in your test just do

page.check('prepay-enrollment-modal-agreement-checkbox', allow_label_click: true)

Note: rather than expect(page).to have_selector("[data-testid='review-step-container']") you should use expect(page).to have_css("[data-testid='review-step-container']") to make it clearer that you know you're passing CSS. Also for test speed reasons you may want to combine all of the have_content calls into one using a regex

  • Related