Home Ask Login Register

Developers Planet

Your answer is one click away!

jrochkind February 2016

How to write tests against code requiring remote OAuth?

I have some code that uses an API to push some data to a remote third-party service.

In actual use, it needs OAuth-generated credentials to push to this API endpoint. That's all working, when the user pushes the 'export' button, we redirect them through the OAuth flow, they come back, we've got a token, we push the data (probably in a bg job, which has it's own potential problems, but that's not the focus of this question), great.

But how do I write an automated test for this functionality? I don't have the OAuth credentials at test time, and I don't know if there's any good way to get them.

I could actually web scrape to fake a user login to real third-party service, but that seems ugly. I could skip the actual "prove it really pushes test", and just test that the request I'm going to send looks right, but I'd love to have an automated test proving that it really does succesfully push, in case the third party changes things. I would probably record it with "vcr" to avoid the slow network requests each time, but that's not the issue either (unless it is because it'll make things even harder...)

In this case, the third-party API uses OAuth 1.0a, if that matters.

Any ideas or solutions? Is this a thing?


max February 2016

OmniAuth has a built in test mode that can be used to short-circuit the actual requests.

OmniAuth.config.test_mode = true

You can simulate a failure with:

OmniAuth.config.mock_auth[:some_provider] = :invalid_credentials

Or setup a response with:

OmniAuth.config.add_mock(:some_provider, {:uid => '12345'})

You would only really do this in tests which cover the authentication system, such as your CallbacksController or integration tests that cover the sign in path.

For everything else you would just stub out the authentication system so that your current_user returns a fixture (or factory) when there should be an authenticated user. Its a lot faster than each integration test retesting the same sign pathway. (click "sign in" ...)

If you are using Warden or Devise they have built in test helpers to do this.

You could record it with VCR, but that introduces issues of what to do with cassettes that might potentially contain sensitive information and how those should be shared between developers.

Usually testing against the actual provider is more of a OmniAuth strategy author concern that you don't need to worry about unless you are creating a strategy for some obscure OAuth provider or creating an OAuth service of your own. If you are using Facebook, Twitter or one of the other big boys then its not a concern.

See also:

Post Status

Asked in February 2016
Viewed 1,270 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life