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

时间:2012-05-06 00:54:58

标签: ruby-on-rails rspec omniauth

我查看了gem wiki并按照说明操作但由于某些原因我在进行omniauth测试时得到了nil

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:

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)

规范结果:

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)>'

1 个答案:

答案 0 :(得分:4)

在测试中尝试使用符号而不是字符串:

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

我不确定Omniauth是否会在某些时候从字符串更改为符号,但似乎有许多示例使用字符串作为键。

为了完整起见,如果有人试图用Devise和Omniauth进行此操作,请不要忘记在之前的块中添加devise.mapping。

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