require 'spec_helper'
require 'google_client'

describe "OAuth", :slow=>true, :js=>true, :type=>:feature, :capybara_feature=>true, intermittent: true do

  subject { page }

  before(:all) do
    Capybara.javascript_driver = :poltergeist
    Capybara.current_driver = Capybara.javascript_driver
    Capybara.default_max_wait_time = 10
    @previous_run_server = Capybara.run_server
    Capybara.run_server = false
    @user=FactoryGirl.create(:user, :email=>"jamkazamtest@gmail.com")    
  end

  before(:each) do
    @youtube_client = GoogleClient.new()
  end

  after(:each) do
    @youtube_client.shutdown if @youtube_client
    @youtube_client=nil
    @user.user_authorizations.destroy_all
    #page.driver.remove_cookie(:remember_token)
  end

  after(:all) do
    @user.destroy 
    Capybara.run_server = @previous_run_server       
  end

  it "client should not authorize a wrong password" do      
    expect {
      authorize_google_user(@youtube_client, @user, "f00bar")
    }.to raise_error

    @user.reload
    @user.user_authorizations.count.should eq(0)    
  end

  it "client should authorize a google user" do      
    authorize_google_user(@youtube_client, @user, "filthyblueberryjam")
    #save_screenshot("working.png")
    @user.reload    
    @user.user_authorizations.count.should eq(1)

    google_auth = UserAuthorization.google_auth(@user).first
    google_auth.should_not be_nil
    google_auth.token.should_not be_nil      
  end

end
