如何为登录编写Omniauth RSpec?

Eri*_*ric 7 rspec ruby-on-rails omniauth

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

如何编写RSpec测试,该测试将遵循所有这些重定向以验证我的用户是否已经过身份验证?

Dmi*_*kel 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)