Testing Twitter OAuth with Cucumber, Webrat, and FakeWeb
I’ve recently seen folks asking questions about how to do acceptance testing with Cucumber on an application that authenticates using Twitter’s OAuth service. Since I’ve recently done exactly that, I thought I’d share my technique with the world. I’ll walk you through it step-by-step here, from creating a new Rails app all the way to the bitter end, but if you’re impatient and just want to see the code you can download the example app here. I would encourage you to take a walk through this tutorial, though, because the example app isn’t entirely self-explanatory. Credit where credit is due: I shamelessly stole the ideas of creating the methods “stub_get”, “stub_post” and friends, as well that of as storing API responses in fixture files, from John Nunemaker’s tests for his excellent Twitter gem, which my application uses. This example app also uses that gem, but because I’m essentially stubbing the Twitter API itself, they should work with whatever you’re using to talk to Twitter (so long as it understands Twitter’s JSON responses). Finally, I’m aware that my blog’s layout isn’t really friendly to code files, and it tends to smush them. If the code below looks strange (and some of it will, I promise) hit the “view plain” button found at the top of each code box to get a better look at it. Sorry about that. Let’s start by creating a new Rails project to play with: