Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure an element is not present with Capybara

Tags:

ruby

capybara

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.

like image 282
michaeltwofish Avatar asked May 06 '11 01:05

michaeltwofish


3 Answers

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

like image 141
Derek Ekins Avatar answered Oct 22 '22 15:10

Derek Ekins


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 . . .

like image 28
5_nd_5 Avatar answered Oct 22 '22 15:10

5_nd_5


Here's what I am using:

expect(page).to have_no_css('.test')
like image 15
nroose Avatar answered Oct 22 '22 16:10

nroose