require 'rails_helper'

RSpec.describe Game, type: :model do
  before(:each) do
    @game = FactoryGirl.create(:game)
    @user1 = FactoryGirl.create(:user)
    @user2 = FactoryGirl.create(:user)
  end

  subject { @game }

  it { should respond_to(:title) }
  it { should respond_to(:play_to_beat) }
  it { should respond_to(:winner) }

  it '#title returns a string' do
    expect(@game.title).to match 'Test Game'
  end

  it 'has a winner' do
    # Start the game
    @player1 = @user1.sit_in(@game.seats.first)
    @player2 = @user2.sit_in(@game.seats.last)
    @game.start

    # controlling player plays all their cards
    @player = @game.controlling_player
    @player.inventory.each do |card|
    @player.play_hand [card]
    @game.reload
      while (@game.controlling_player != @player) do
        @game.controlling_player.pass
        @game.reload
      end
    end

    expect(@game.winner).to eq @player
  end

  describe 'validations' do
    describe 'player_count' do
      context 'when there are 2 to 4 players' do
        it 'is startable' do
          @game.add_player_from_user(@user1)
          @game.add_player_from_user(@user2)
          expect(@game.players.size).to eq(2)
          expect(@game.startable?).to eq(true)
        end
      end

      context 'when there are less than 2 players' do
        it 'is not startable with too few players' do
          expect { @game.validate_startable }.to raise_error StandardError
          expect(@game.players.size).to eq(0)
          expect(@game.startable?).to eq(false)
          expect(@game.errors[:players])
            .to include 'Must be at least 2 players.'
        end
      end
      context 'when there are more than 4 players' do
        it 'fails validation with too many players' do
          6.times do
            @user = FactoryGirl.create(:user)
            @player = @game.players.new(user_id: @user.id)
            @player.save
          end
          @game.players.new(user_id: User.last.id)
          expect { @game.validate_startable }.to raise_error StandardError
          expect(@game.startable?).to eq(false)
          expect(@game.errors[:players])
            .to include 'Must be less than 5 players.'
        end
      end
    end
  end
end
