使用oauth-plugin gem在rspec测试中测试OAuth2请求

时间:2012-03-21 16:12:05

标签: ruby-on-rails rspec oauth-2.0

我在Rails 3.1中使用最新的oauth-plugin。我想用rspec测试来测试我的 OAuth2 API控制器。在尝试了一堆事情来授权我的请求之后,我只想简单地删除 oauthenticate 过滤器来解决任何身份验证问题。但我仍然得到 401 Unauthorized 。为什么?

users_controller.rb:

class UsersController
  oauthenticate

  def update
    <do something>
  end
end

users_controller_spec.rb:

describe UsersController do
  describe "POST 'update'" do

      before :each do
        controller.stub!(:oauthenticate).and_return true
      end

      it "should be a successful request" do
        post :update,  { "user_id" => "some id" }
        response.should be_ok
     end
end

预期的ActionController :: TestResponse的响应代码为200,但得到了401。

Rspec testing for oauth provider无济于事。使用黄瓜测试时,设置有效的访问令牌授权标题时,一切正常。

3 个答案:

答案 0 :(得分:2)

好的我还是不知道为什么 oauthenticate 没有被删除,但我想通了,如何在RSpec测试中进行经过身份验证的OAuth2请求。您必须设置请求对象的 oauth.strategies 令牌参数:

def prepare_authenticated_access_token_request
   # Create consumer application
   @client_application = Factory.create(:client_application)
   # Create a user who authorized the consumer
   @resource_owner = Factory.create(:user)
   # Create a valid, authorized access token
   token = Oauth2Token.create :user => @resource_owner, :client_application => @client_application
   # Configure the request object so that it is recognized as a OAuth2 request
   request.env["oauth.strategies"] = [:oauth20_token, :token]
   request.env["oauth.token"] = token
 end

答案 1 :(得分:2)

与Peter的答案类似,除了更好一点,因为它只会在本规范的上下文中存根该方法:

before :each do
  OAuth::Controllers::ApplicationControllerMethods::Filter.
    any_instance.stub(:filter).and_return(true)
end

答案 2 :(得分:1)

你的存根方法不起作用,因为只要加载了类就调用了oauthenticate,所以当你的存根是在控制器上已经设置了之前的过滤器时。

我通过重新定义基础过滤方法找到了解决方法,如下所示:

before :each do
  OAuth::Controllers::ApplicationControllerMethods::Filter.class_eval do
    def filter(controller)
      return true
    end
  end
end

我发现这比创建oauth令牌和标题更清晰,但当然它不再测试你的身份验证。