I am using Cucumber and Capybara. I need to make an HTTP DELETE
request. Previously the features used webrat, so a simple statement like
visit "/comment/" + comment_id, :delete
worked, but now I am using Capybara.
The way to do a GET
request is simply:
get 'path'
And to do a post request:
page.driver.post 'path'
But how can I simulate a DELETE
request?
I found out that the driver Capybara is using is Capybara::RackTest::Driver
, if that is any help.
I have also tried:
Capybara.current_session.driver.delete "/comments/" + comment_id
But that does not work.
page.driver.submit :delete, "/comments/#{comment_id}", {}
Documentation at: http://rubydoc.info/gems/capybara/1.1.2/Capybara/RackTest/Browser:submit
In case you are using a driver that doesn't support custom HTTP requests (e.g. Capybara-webkit, see closed issue and current driver), you could just temporary switch to RackTest driver to submit your request.
For example:
# Submit an HTTP delete request, using rack_test driver
def http_delete path
current_driver = Capybara.current_driver
Capybara.current_driver = :rack_test
page.driver.submit :delete, path, {}
Capybara.current_driver = current_driver
end
page.driver.delete("/comments/#{comment_id}")
Use delete
works fine. No need to use the lower level submit
method for this.
PS: tested with capybara-webkit 1.6.0 and capybara 2.4.4
If you need a solution that will retain session information (e.g., if you need your DELETE
request to be issued as an authenticated user), and that will work with both the :rack_test
driver and the :webkit
driver (assuming you have jQuery available in your app), try something like this:
def manual_http_request(method, path)
if Capybara.current_driver == :rack_test
page.driver.submit method, path, {}
else
page.execute_script("$.ajax({url: '#{path}', data: {}, type: '#{method}'});")
# Wait for the request to finish executing...
Timeout.timeout(10) { loop until page.evaluate_script('jQuery.active').zero? }
end
end
I suspect this will also work with the :selenium
driver but have not tested it. Maybe someone else can chime in on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With