require 'spec_helper'

describe "Welcome", :js => true, :type => :feature, :capybara_feature => true  do

  subject { page }

  before(:all) do
    Capybara.javascript_driver = :poltergeist
    Capybara.current_driver = Capybara.javascript_driver
    Capybara.default_max_wait_time = 10
  end

  let(:user) { FactoryGirl.create(:user, email: 'twitter_user1@jamkazam.com') }
  let(:user2) { FactoryGirl.create(:user, email: 'twitter_user2@jamkazam.com') }
  let(:twitter_auth) {
    {     :provider => "twitter",
          :uid      => "1234",
          :credentials => {:token => "twitter_token", :secret => 'twitter_secret'} }
  }


  before(:each) do

    OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new(twitter_auth)
    User.where(email: 'twitter_user1@jamkazam.com').delete_all
    User.where(email: 'twitter_user2@jamkazam.com').delete_all

    emulate_client
    sign_in_poltergeist user
    visit "/"
    should_be_at_root
  end

  it "redirects back when done, and updates user_auth" do
    visit '/auth/twitter'
    should_be_at_root
    sleep 1
    user.reload
    auth = user.user_authorization('twitter')
    auth.should_not be_nil
    auth.uid.should == '1234'
    auth.token.should == 'twitter_token'
    auth.secret.should == 'twitter_secret'

    visit '/auth/twitter'
    should_be_at_root
    user.reload
    auth = user.user_authorization('twitter')
    auth.uid.should == '1234'
    auth.token.should == 'twitter_token'
    auth.secret.should == 'twitter_secret'
  end

  it "shows error when two users try to auth same twitter account" do
    visit '/auth/twitter'
    should_be_at_root
    sleep 1
    user.reload
    auth = user.user_authorization('twitter')
    auth.uid.should == '1234'

    sign_out

    sign_in_poltergeist user2
    visit '/'
    should_be_at_root
    visit '/auth/twitter'
    find('li', text: 'This twitter account is already associated with someone else')
  end

end

