Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a submit button exists in capybara?

I want to have a test in rspec for the existence of a submit button. I am using capybara as well.

I have tried:

should have_tag("input","Submit button")

and

should have_content("Submit, button")

but it either raises an exception or gives false positives.

like image 326
sonnyhe2002 Avatar asked Sep 24 '12 21:09

sonnyhe2002


2 Answers

These are all good suggestions, but if you want to confirm that it's a button and that it has the right value (for display), you have to be a little more detailed:

page.should have_selector("input[type=submit][value='Press Me']")

I don't know of an existing matcher that does this. Here's a custom RSpec2 matcher I wrote:

RSpec::Matchers.define :have_submit_button do |value|
  match do |actual|
    actual.should have_selector("input[type=submit][value='#{value}']")
  end
end

Here's the RSpec3 version (courtesy @zwippie):

RSpec::Matchers.define :have_submit_button do |value|
  match do |actual|
    expect(actual).to have_selector("input[type=submit][value='#{value}']")
  end
end

I keep it in spec/support/matchers/request_matchers.rb with my other custom matchers. RSpec picks it up automatically. Since this is an RSpec matcher (rather than a Capybara finder), it will work in both feature specs (Capybara) and view specs (RSpec without Capybara).

Feature spec usage:

page.should have_submit_button("Save Me")

View spec usage (after calling render):

rendered.should have_submit_button("Save Me")

Note that if you're in a Capybara request spec, and you would like to interact with a submit button, that's a lot easier:

click_button "Save Me"

There's no guarantee that it's actually a submit button, but your feature specs should just be testing the behavior and not worrying about that level of detail.

like image 155
Jim Stewart Avatar answered Sep 29 '22 19:09

Jim Stewart


There is a built-in matcher has_button?.

Using RSpec you can have an assertion like

page.should have_button('Submit button')

Or with new RSpec 3 syntax:

expect(page).to have_button('Submit button')
like image 43
koffeinfrei Avatar answered Sep 29 '22 18:09

koffeinfrei