2012-03-21 58 views
0

我在Rails 3.1中使用最新的oauth-plugin。我想用rspec测试来测试我的OAuth2 API控制器。在尝试了许多事情来授权我的请求之后,我只想简化认证过滤器以摆脱任何身份验证问题。但我仍然收到一个401 Unauthorized。为什么??使用oauth-plugin gem在rspec测试中测试OAuth2请求

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没有按”帮助。随着黄瓜测试一切正常,当设置一个有效的访问令牌授权标题

回答

2

好的我仍然不知道为什么认证变得不存在,但我想通过RSpec测试如何进行认证的OAuth2请求。你必须设置oauth.strategies令牌参数request对象:

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

您的磕碰做法没有奏效,因为oauthenticate是只要类加载调用,所以,当你的时候存根是先前在控制器上设置的过滤器。

我找到解决的办法重新定义底层的过滤方法,如下所示:

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

我发现这个吸尘器不必创建OAuth凭证和头,但当然它不检查您的身份验证了。

2

类似彼得的回答,只是有点漂亮,因为它只会在存根本规范的上下文中的方法:

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