Capybara POST requests

Force Ruby’s Capybara gem to make an HTTP POST request even when it’s not recommended.

The Capybara Ruby gem doesn’t support POST requests, the built-in visit method always uses GET. This is by design and with good reason: Capybara is built for acceptance testing and a user would never ask to ‘post’ parameter X and Y to the application. There will always be some kind of interface, a form for example. It makes more sense to simulate what the visitor would really do:

  fill_in 'Login', :with => 'user@example.com'
  fill_in 'Password', :with => 'password'
  click_link 'Sign in'
  

POSTing with Capybara

So far for the obligatory warning. I get the point, I even agree with the argument, but I still want to send a POST request. Maybe you are testing an API without a user interface or you are writing router tests? Is it really impossible to simulate a POST request with Capybara? Nah, of course not!

  it "registers a new temperature reading via the API" do
    page.driver.post('/temperature/new', { :params => { :degrees => "30" } }) 
    page.driver.status_code.should eql 200
  end
  

Note that the second line is questionable as well. It asks the response status code from the driver but not every driver supports this. The example works with certain web drivers but is not recommended.

There is a similar issue when clicking a link without text (an image for example) in Capybara.

In summary: always try to think from the visitor’s point of view. How would someone explain what they are doing over the phone for example? Use the first method where possible but know you can fall back to the custom POST method if needed.

This post is open source. Did you spot a mistake? Ideas for improvements? Contribute to this post via Github. Thank you!