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, "https://github.com/", :body => "Awesome")

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

Net::HTTP.get(URI.parse("http://github.com"))
=> "Awesome"

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

FakeWeb.register_uri(:get, "https://github.com/login/oauth/access_token?client_id=#{Settings.github_client_id}&client_secret=#{Settings.github_client_secret}&code=123", :body => "token=token_123")
FakeWeb.register_uri(:get, "https://api.github.com/user?access_token=token_123", :body => "{\"id\": 1, \"email\": \"test@test.de\"}")

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.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s