For this chapter, we'll be examining the within
method, which allows us to search within a section of a page.
Let's say you have a form and there's supposed to be two checkboxes on the page: checkbox 1 and checkbox 2.
How you can you determine that not only are the checkboxes there but they're also in a specific form?
If we were to inspect one of the checkboxes, you can see they are captured in a form with the id
called “checkboxes”. An abbreviation for an id
is the pound sign or hashtag (#).
So, you can see that locator for this form is “form#checkboxes”. We can use that with our test.
Going back to our project, let's go into test number 2 — the feature we're testing is the within
command.
Let's test the feature
“Within: Scoping”.
scenario 'Within (Checkboxes): checkbox 1' do
within('form#checkboxes') do
expect(page).to have_content('checkbox 1')
end
end
Here we go to set the test up by going to the checkboxes and to verify that checkbox 1 is on the page we're going to go within the checkbox form and expect the page to have the content “checkbox 1”.
For a second test, we're going to go within the checkbox form and expect the page to have the content “checkbox 2”.
Let's run the test, this time kicking off spec/features/02
, hit tab to complete:
bundle exec rspec spec/features/02_within_spec.rb
And you can see that everything passed.
Let's say we wanted check within the page footer that the link, "Elemental Selenium" appears.
That page footer has a locator div#page-footer.row
.
scenario 'Within (Page Footer): Elemental Selenium' do
within('div#page-footer.row') do
expect(page).to have_link('Elemental Selenium')
end
end
That's a bit clunky.
Instead, let's take that locator and put it in a constant.
PAGE_FOOTER = 'div#page-footer.row'
scenario 'Within (Page Footer): Elemental Selenium' do
within(PAGE_FOOTER) do
expect(page).to have_link('Elemental Selenium')
end
end
Yeah, it's something a bit more readable that we're going within
the page footer.
Capybara also has for the within
command within the fieldset and within table
within_fieldset('Employee') do
fill_in 'Name', with: 'Jimmy'
end
within_table('Employee') do
fill_in 'Name', with: 'Jimmy'
end
Say for example, you wanted to search within the employee fieldset, you can fill in the name field with a value of “Jimmy”, or within the employee table, you can fill in the name field with a value.
You can read more about this by going to the Capybara GitHub page and selecting Scoping, where you can see it also work within Windows.
For our next section, we're going to be exploring the Login Page, entering both valid and invalid credentials.