Rails: How to test an OAuth Provider controller in a functional test
Suppose you have a controller that is an OAuth Provider. It rejects requests that do not have proper OAuth signatures and accepts only requests that do. You would like to test this controller in a functional test.
It is not (to me, anyway) obvious how to do this with the ruby-oauth gem. After many hours of scouring through the code and trial-and-error, I came to the following solution. Basically, use OAuth::RequestProxy::MockRequest
to generate a proper Authorization header complete with the signature, and then tack that on to the @request
object.
In my design, the test cases have a predefined consumer key/secret and access token, which may make things simpler.
url = url_for({ :controller => 'contexts', :action => 'index', :id => 'blahblah' })
rp = OAuth::RequestProxy.proxy(
"method" => "GET",
"uri" => url,
"parameters" => {
# IMPORTANT: any URL parameters must go here also... should parse url and merge the params in here
"oauth_consumer_key" => TEST_CONSUMER_KEY,
"oauth_token" => TEST_ACCESS_TOKEN,
"oauth_nonce" => "vaopfijv3498fjua9pewr8jaa",
"oauth_timestamp" => Time.now.to_i,
"oauth_signature_method" => "HMAC-SHA1"
}
)
rp.sign!({
:consumer_secret => TEST_CONSUMER_SECRET,
:token_secret => TEST_ACCESS_TOKEN_SECRET
}
)
@request.env['Authorization'] = rp.oauth_headerget :index, :id => "blahblah"
assert_response(:success)
Ideally, I would use the subclass of OAuth::RequestProxy
that handles ActionController::Request
directly instead of the MockRequest
but I did not have luck with that. It was partially due to this bug. I might try again some time but this is working for now.
Note that I'm using url_for
in the test, which I mentioned before here.
References: