简体   繁体   English

你如何使用rspec测试omni-auth facebook?

[英]How do you test omni-auth facebook using rspec?

I've looked at the gem wiki and followed the instructions but for some reason I am getting a nil when doing an omniauth test: 我看了一下gem wiki并按照说明进行操作但由于某些原因我在进行omniauth测试时得到了一个nil

user_sessions_controller_spec.rb: user_sessions_controller_spec.rb:

require 'spec_helper'

describe UserSessionsController, "OmniAuth" do
  before do
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
  end

  it "sets a session variable to the OmniAuth auth hash" do
    request.env["omniauth.auth"]['uid'].should == '123545'
  end
end

spec_helper.rb: spec_helper.rb:

RACK_ENV = ENV['ENVIRONMENT'] ||= 'test'
OmniAuth.config.test_mode = true
omniauth_hash =
    {:provider => "facebook",
     :uid      => "1234",
     :info   => {:name       => "John Doe",
                 :email      => "johndoe@email.com"},
     :credentials => {:token => "testtoken234tsdf"}}

OmniAuth.config.add_mock(:facebook, omniauth_hash)

spec result: 规格结果:

Failures:

  1) UserSessionsController OmniAuth sets a session variable to the OmniAuth auth hash
     Failure/Error: request.env["omniauth.auth"]['uid'].should == '123545'
     NoMethodError:
       You have a nil object when you didn't expect it!
       You might have expected an instance of Array.
       The error occurred while evaluating nil.[]
     # ./spec/controllers/user_sessions_controller_spec.rb:10:in `block (2 levels) in <top (required)>'

Try a symbol in your test rather than a string: 在测试中尝试使用符号而不是字符串:

  it "sets a session variable to the OmniAuth auth hash" do
    request.env["omniauth.auth"][:uid].should == '1234'
  end

I'm not sure if Omniauth changed from strings to symbols at some point but there seems to be a number of examples out there using strings as keys. 我不确定Omniauth是否在某些时候从字符串变为符号,但似乎有很多例子使用字符串作为键。

Just for completeness, if anyone is trying to do this with Devise and Omniauth, don't forget to add the devise.mapping in the before block. 只是为了完整性,如果有人试图用Devise和Omniauth做这个,不要忘记在前一个块中添加devise.mapping。

before do
  request.env["devise.mapping"] = Devise.mappings[:user]
  request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM