How to mock the GitHub API

If you write code against the GitHub API you have to mock it somehow. Otherwise it can be tricky to test it. Here is how I did it. I found this great GEM FakeWeb. With this GEM you can fake Web Requests. It allows you to register URLs with fix responses. Her is an example:

FakeWeb.register_uri(:get, "", :body => "Awesome")

If you do now a HTTP request to you will get “Awesome” as response.

=> "Awesome"

Here is how I mocked the GitHub OAuth login precess. I just registered this 2 URLs:

FakeWeb.register_uri(:get, "{Settings.github_client_id}&client_secret=#{Settings.github_client_secret}&code=123", :body => "token=token_123")
FakeWeb.register_uri(:get, "", :body => "{\"id\": 1, \"email\": \"\"}")

And that’s it. With that you can now test your callback.

get "/auth/github/callback?code=123"
assert_response :success

I am using RSpec for testing. Let me know if you have questions.

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: