require 'spec_helper'

describe SessionsController do
  render_views
  
  describe "GET 'new'" do
    it "should work" do
      get :new
      response.should be_success  
    end
    
    it "should have the right title" do
      get :new
      response.body.should have_title("JamKazam | Sign in")
    end
  end
  
  
  describe "POST 'create'" do
    before(:each) do
      @user = FactoryGirl.create(:user)
      @attr = { :email => @user.email, :password => @user.password }
    end
    
    it "should sign the user in" do
      post :create, :session => @attr
      controller.current_user.should == @user      
      controller.signed_in?.should == true
    end
    
    it "should redirect the user to the proper page" do      
      post :create, :session => @attr
      response.should redirect_to(client_url)      
    end

  end
  
  describe "create_oauth" do
    
    before(:each) do
    OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
          'uid' => '100',
          'provider' => 'facebook',
          'info' => {
            'first_name' => 'FirstName',
            'last_name' => 'LastName',
            'email' => 'test_oauth@example.com',
            'location' => 'mylocation'
          },
          'credentials' => {
            'token' => 'facebooktoken',
            'expires_at' => 1000000000
          }
        })       
    end
    
    it "should create a user when oauth comes in with a non-currently existing user" do
      pending "needs this fixed: https://jamkazam.atlassian.net/browse/VRFS-271"
      request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook] 
      lambda do
        visit '/auth/facebook'
      end.should change(User, :count).by(1)      
      user = User.find_by_email('test_oauth@example.com')
      user.should_not be_nil
      user.first_name.should == "FirstName"
      response.should be_success
      
      # also verify that a second visit does *not* create another new user
      lambda do
        visit '/auth/facebook'
      end.should change(User, :count).by(0)
    end
    
    
    it "should not create a user when oauth comes in with a currently existing user" do
      user = FactoryGirl.create(:user)  # in the jam session
      OmniAuth.config.mock_auth[:facebook][:info][:email] = user.email 
      OmniAuth.config.mock_auth[:facebook] = OmniAuth.config.mock_auth[:facebook] 
      
      lambda do
        visit '/auth/facebook'
      end.should change(User, :count).by(0)
    end
    
  end
  
  
end
