7

当用户访问时,它会被重定向到 FB,如果成功/auth/facebook则返回我的。/auth/facebook/callback

如何编写一个 RSpec 测试来遵循所有这些重定向来验证我的用户是否已通过身份验证?

4

1 回答 1

6

我会推荐一种替代的、更简单的方法。如果您直接测试回调控制器以查看它对omniauth.auth 中传递给它的不同值的反应,或者如果env[“omniauth.auth”] 丢失或不正确,该怎么办。以下重定向相当于测试omniauth 插件,它不会测试您的系统。

例如,这是我们在测试中的内容(这只是几个示例,我们还有更多示例可以在登录尝试之前验证omniauth 哈希和用户状态的其他变体,例如邀请状态、用户帐户被禁用管理员等):

describe Users::OmniauthCallbacksController do
  before :each do
    # This a Devise specific thing for functional tests. See https://github.com/plataformatec/devise/issues/608
    request.env["devise.mapping"] = Devise.mappings[:user]
  end
  describe ".create" do

    it "should redirect back to sign_up page with an error when omniauth.auth is missing" do
      @controller.stub!(:env).and_return({"some_other_key" => "some_other_value"})
      get :facebook
      flash[:error].should be
      flash[:error].should match /Unexpected response from Facebook\./
      response.should redirect_to new_user_registration_url
    end

    it "should redirect back to sign_up page with an error when provider is missing" do
      stub_env_for_omniauth(nil)
      get :facebook
      flash[:error].should be
      flash[:error].should match /Unexpected response from Facebook: Provider information is missing/
      response.should redirect_to new_user_registration_url
    end
  end
end

方法stub_env_for_omniauth定义如下:

def stub_env_for_omniauth(provider = "facebook", uid = "1234567", email = "bob@contoso.com", name = "John Doe")
  env = { "omniauth.auth" => { "provider" => provider, "uid" => uid, "info" => { "email" => email, "name" => name } } }
  @controller.stub!(:env).and_return(env)
  env
end
于 2012-09-22T20:21:38.930 回答