Ensure an element is not present with Capybara

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')

I tried the solution suggested by Derek, however, I ran into some false negatives.

That is

page.should have_no_selector(:xpath, "//input[@type='#{type}' and @name='#{name}']")

passes even when it should fail for some reason.

I have found success with the RSpec syntax of raise_error

expect { find(:xpath, "//input[@type='#{type}' and @name='#{name}']") }.to raise_error

I think this is closer to what you're asking anyway. So I put this forward as an answer.

Tags:

Ruby

Capybara