Capybara matcher for presence of button or link

Updated answer (should matcher is deprecated in RSpec 3.0+):

expect(page).to have_selector(:link_or_button, 'Click me')

Before:

page.should have_selector(:link_or_button, 'Click me')

Followed from click_link_or_button which is defined here: https://github.com/jnicklas/capybara/blob/master/lib/capybara/node/actions.rb#L12

def click_link_or_button(locator)
  find(:link_or_button, locator).click
end
alias_method :click_on, :click_link_or_button

It calls a selector :link_or_button. This selector is defined here: https://github.com/jnicklas/capybara/blob/master/lib/capybara/selector.rb#L143

Capybara.add_selector(:link_or_button) do
  label "link or button"
  xpath { |locator| XPath::HTML.link_or_button(locator) }
end

It calls this method: http://rdoc.info/github/jnicklas/xpath/XPath/HTML#link_or_button-instance_method

# File 'lib/xpath/html.rb', line 33

def link_or_button(locator)
  link(locator) + button(locator)
end

So i tried to check the presence of the selector and it worked:

page.should have_selector(:link_or_button, 'Click me')

Personally I would give your button or link an id and look for that using

page.should have_css('#foo')

This way you can refer to the link or button without worrying about its implementation.

I always find this useful: https://gist.github.com/428105


You can also use a custom matcher

RSpec::Matchers::define :have_link_or_button do |text|
  match do |page|
    Capybara.string(page.body).has_selector?(:link_or_button, text: text)
  end
end

Then do

expect(page).to have_link_or_button('Login')

Using the expect syntax

expect(page).to have_selector(:link_or_button, 'Click me')

This works without needing to define a custom matcher.