How do you test omni-auth facebook with rspec?

I looked at the gem wiki and followed the instructions, but for some reason I get nilomniauth when I run the test:

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)

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)>'
+5
source share
1 answer

Try using a character 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 that Omniauth at some point changed from strings to characters, but there seem to be a number of examples using strings as keys.

Just for completeness, if someone is trying to do this with Devise and Omniauth, be sure to add devise.mapping in the previous block.

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

All Articles