Last Updated: February 25, 2016
·
897
· mixandgo

omniauth multiple user login

For multi user / social sites that often need to test user interactions (like friends actions) you need a way to test 2 or more users interacting at the same time. So here's a snippet I've used:

Sample capybara scenario:

scenario "User's friends recipes show up on his home page", :js => true do
  user = FactoryGirl.create(:user)
  friend = add_friend_for(user)

  in_browser(:friend) do
    login(friend)
    add_recipe("Apple pie)
 end

  in_browser(:user) do
    login(user)
    click_on "Home"
    page.should have_css('.friend_recipes .recipe', :text => "Apple pie")
  end
end

And here is what you need to make it work:

# /spec/support/omniauth.rb
OmniAuth.config.test_mode = true

def omniauth_mock(user = nil)
  user ||= FactoryGirl.create(:user)

  OmniAuth.config.mock_auth[:facebook] = {
    :uid => user.uid,
    :provider => user.provider,
    :info => {:name => user.name, :nickname => 'fbuser'},
    :credentials => {:token => user.email, :expires_at => 2.days.from_now},
    :extra => {"user_hash" => {:id => user.id, :email => user.email}}
  }
end

# /spec/factories/users.rb
FactoryGirl.define do
  sequence :email do |n|
    "test#{n}@email.com"
  end

  factory :user do
    sequence(:name) { |n| "John Doe#{n}" }
    email { FactoryGirl.generate(:email) }
    sequence(:provider) { |n| "facebook#{n}" } # Hack-ish way to log in multiple users at the same time
    sequence(:uid) {|n| "uid#{n}"}
    oauth_token "1234567890"
  end
end

 # capybara helper (I put helpers in /spec/support/common_steps.rb)
def login(user = nil)
  omniauth_mock(user)
  visit root_path
  click_on "Login"
end

def in_browser(name)
  Capybara.session_name = name
  yield
end