Using Capybara, I need to assert that a form element is not present, for example, 'Then I should not see the "Username" text field'. As find throws an exception if the element isn't found, this is the best I've come up with. Is there a better way?
Then /^I should not see the "([^\"]+)" ([^\s]+) field$/ do |name, type|
begin
# Capybara throws an exception if the element is not found
find(:xpath, "//input[@type='#{type}' and @name='#{name}']")
# We get here if we find it, so we want this step to fail
false
rescue Capybara::ElementNotFound
# Return true if there was an element not found exception
true
end
end
I'm new to Capybara, so I may be missing something obvious.
You can do this by making use of capybaras has_no_selector? method combined with rspecs magic matchers. You can then use it in this way:
page.should have_no_selector(:xpath, "//input[@type='#{type}' and @name='#{name}']")
You can see more details of the assertions you can perform on the capybara documentation page here under the section entitled Querying
You can actually use already existing methods defined by Capybara matchers.
assert has_no_field?('Username')
Furthermore there are additional methods available the can help you in finding different types of elements in your page
has_link? , has_no_link?
has_button?, has_no_button?
has_field?, has_no_field?
has_checked_field?, has_no_checked_field?
has_select?, has_no_select?
And many more . . .
Here's what I am using:
expect(page).to have_no_css('.test')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With