【问题标题】:Omniauth-facebook Devise Rspec, undefined method `extra' for nil:NilClassOmniauth-facebook 设计 Rspec,nil:NilClass 的未定义方法“额外”
【发布时间】:2012-06-19 12:35:36
【问题描述】:

我正在尝试在我的应用程序中测试omniauth-facebook 集成,但我不断遇到这种失败:

Failure/Error: get :facebook
 NoMethodError:
   undefined method `extra' for nil:NilClass
 # ./app/models/user.rb:17:in `find_for_facebook_oauth'
 # ./app/controllers/users/omniauth_callbacks_controller.rb:4:in `facebook'
 # ./spec/controllers/users/omniauth_callbacks_controller_spec.rb:18:in `block (4 levels) in <top (required)>'

这是引发失败的代码行:

user.rb

def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
  data = auth.extra.raw_info # this is line 17
  if user = User.where(:email => data.email).first
    user
  else
    user = User.new
    user
  end
end

omniauth_callbacks_controller.rb

def facebook
  @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user) # this is line 4

  if @user.persisted?
    flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
    sign_in_and_redirect @user, :event => :authentication
  else
    flash[:notice] = "Authentication was successful, please continue your registration process."
    session["devise.facebook_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
end

omniauth_callbacks_controller_spec.rb

before(:each) do
  stub_env_for_omniauth

  get :facebook # this is line 18
  @user = User.where(:email => "ghost@nobody.com").first
end

def stub_env_for_omniauth
  request.env["devise.mapping"] = Devise.mappings[:user]
  pre = { "omniauth.auth" => { "provider" => "facebook", "uid" => "1234", "credentials" => {"token" => "abcdefg"}, "extra"=>{"raw_info" => {"id" => "1234567", "email" => "ghost@nobody.com", "name" => "Mark", "gender" => "male" }}}}
  env = OmniAuth::AuthHash.new(pre)
  @controller.stub!(:env).and_return(env)
end

这是 spec_helper.rb

require 'omniauth'
OmniAuth.config.test_mode = true

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails rspec devise omniauth


    【解决方案1】:

    我认为你应该设置而不是@controller.stub!

    request.env["omniauth.auth"] = env
    

    在此处阅读有关测试omniauth的更多信息https://github.com/intridea/omniauth/wiki/Integration-Testing

    【讨论】:

    【解决方案2】:

    嘿,只需在 facebook 方法中添加以下行

    def facebook
    raise request.env["omniauth.auth"].to_yaml
    ....
    end
    

    然后检查您从 facebook-omniauth 得到的响应。这可能有助于您发现问题。

    【讨论】:

    • 这是我得到的输出http://pastebin.com/8qDx4htX
    • 这是我为测试添加的哈希(在 stub_env_for_omniauth 方法中)
    • omniauth 哈希有问题。您没有获得用户的完整详细信息,这就是为什么您将“额外”字段设为 nil。我认为您的规范没有问题..
    猜你喜欢
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多