【问题标题】:Test OAuth2 request in rspec test with oauth-plugin gem使用 oauth-plugin gem 在 rspec 测试中测试 OAuth2 请求
【发布时间】:2012-03-21 16:12:04
【问题描述】:

我在 Rails 3.1 中使用最新的 oauth 插件。我想用 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 没有帮助。使用黄瓜测试设置有效的访问令牌时一切正常授权标头

【问题讨论】:

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


    【解决方案1】:

    好的,我仍然不知道为什么 oauthenticate 不会被存根,但我想出了如何在 RSpec 测试中发出经过身份验证的 OAuth2 请求。您必须设置请求对象的 oauth.strategiestoken 参数:

    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
    

    【讨论】:

      【解决方案2】:

      类似于彼得的回答,除了更好一点,因为它只会在本规范的上下文中存根方法:

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

      【讨论】:

        【解决方案3】:

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

        我通过重新定义底层过滤方法找到了解决方法,如下:

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

        我发现这比创建 oauth 令牌和标头更简洁,当然它不再测试您的身份验证。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-12
          • 2011-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多