A Capybara Gift From Past Robin

I’m writing this here so that the next time it comes up, I have a permanent record of my solution to this repeating problem:

How do I tell Capybara to follow the redirect after a POST/PUT/DELETE request?

There are likely others like me. Others lost in the bewilderness, pinging between dismissive Stack Overflow answers, blog posts whose solutions refuse to work 1, and the oh-so-helpful folk who dismiss the problem outright, claiming that you should only ever use Capybara through happy little forms and links.

Sometimes, a guy’s just gotta GET, POST, PUT, or DELETE direct to the server. No web form, no anchor tag. Just you and a web API.

The traditional wisdom is that you can call methods like:

page.driver.post(path, param_hash)

… and that’ll send a POST request (or equivalent PUT/DELETE) with Capybara. This doesn’t help me, because these methods won’t follow the traditional RESTful redirect response as I needed. This is what I eventually found in Capybara’s source:

def follow(method, path, attributes = {}) ...

AHA! Gotcha. The secret revealed itself. Just call follow on the page driver instead of get/post/put/delete.

In my case, I used:

page.driver.follow(:put, "/users/#{user_id}", {user: data})

No env.rb tricks, no new gems.

You’re welcome, Future Robin.

Notes:

  1. Also, whose link from Stack Overflow is now dead, but luckily can eventually be found because the author reposted it

Robin Miller

http://www.gentlemanscientist.net

View more posts from this author