Rspec testing for oauth provider

2019-04-29 17:02发布

问题:

I'm writing a API that's also an OAuth provider. Is there any recommended way to write your rspec tests?

After you enable oauth to protect all of your endpoints, how do you write rspec tests that will pass the authentication step?

回答1:

If you are using the oauth and oauth-plugin gems, this post might help you: http://peachshake.com/2010/11/11/oauth-capybara-rspec-headers-and-a-lot-of-pain/


Yet, the oauth-plugin gem generates some specs which include a helper to help you simulate the authentication process.

Take a look at this file: https://github.com/pelle/oauth-plugin/blob/v0.4.0.pre4/lib/generators/rspec/templates/controller_spec_helper.rb

You can use the following methods to sign your requests:

def sign_request_with_oauth(token=nil,options={})
  ActionController::TestRequest.use_oauth=true
  @request.configure_oauth(current_consumer,token,options)
end

def two_legged_sign_request_with_oauth(consumer=nil,options={})
  ActionController::TestRequest.use_oauth=true
  @request.configure_oauth(consumer,nil,options)
end

def add_oauth2_token_header(token,options={})
  request.env['HTTP_AUTHORIZATION'] = "OAuth #{token.token}"
end

I suggest you to copy this file as a helper for your specs and modify accordingly to your needs.