ruby-on-railsrspeccapybara

How to click the form commit button in Capybara


With Rails, rspec and capybara, I'm trying to test your typical ERB generated form:

<form action="/pages/1" id="edit_page_1" method="post">
  <input id="page_title" name="page[title]" type="text">
  <input name="commit" type="submit" value="Update Page">
</form>

I run two kinds of feature specs, those that are the same no matter what the language, and those that are I18N specific (for internationalization testing).

The problem is there is no clear way to click that submit button with capybara, unless I'm missing the obvious. I would expect simply click('commit') to do the trick.


Solution

  • In the end a macro was the answer I needed as apparently there is nothing native in capybara.

    # spec/support/form_helpers.rb
    module FormHelpers
      def submit_form
        find('input[name="commit"]').click
      end
    end
    

    This gets included in spec_helper.rb

    RSpec.configure do |config|
      config.include FormHelpers, :type => :feature
      ...etc...
    

    I used :type => :feature so it gets included only in the integration tests.

    In the integration tests you can use it like this:

    scenario 'pages can be created' do
      visit new_page_path
      fill_in 'page_title', with: 'A Tale of Two Cities'
      submit_form # Clicks the commit button regardless of id or text
    
      expect(page).to have_content 'The page was created'
      ...etc..
    end
    

    Of course submit_form can also be used inside within blocks and with :js => true.