RSpec.describe MetasploitDataModels::AutomaticExploitation::MatchResult, type: :model do
  it_should_behave_like 'Metasploit::Concern.run'

  context "database" do
    it { is_expected.to have_db_column(:match_id).of_type(:integer) }
    it { is_expected.to have_db_index(:match_id) }
    it { is_expected.to have_db_column(:run_id).of_type(:integer) }
    it { is_expected.to have_db_index(:run_id) }
  end

  context 'associations' do
    it { is_expected.to belong_to(:match).class_name('MetasploitDataModels::AutomaticExploitation::Match') }
    it { is_expected.to belong_to(:run).class_name('MetasploitDataModels::AutomaticExploitation::Run') }
  end

  context 'scopes' do
    before do
      match_failed    = FactoryGirl.create(:automatic_exploitation_match)
      match_succeeded = FactoryGirl.create(:automatic_exploitation_match)
      run             = FactoryGirl.create(:automatic_exploitation_run)

      described_class.create do |match_result|
        match_result.match = match_failed
        match_result.run   = run
        match_result.state = MetasploitDataModels::AutomaticExploitation::MatchResult::SUCCEEDED
      end

      described_class.create do |match_result|
        match_result.match = match_succeeded
        match_result.run   = run
        match_result.state = MetasploitDataModels::AutomaticExploitation::MatchResult::FAILED
      end
    end

    context 'succeeded' do
      subject(:succeeded) do
        described_class.succeeded
      end

      specify 'returns only successful results' do
        expect(succeeded.count).to eq(1)
        expect(succeeded.first.state).to eq(MetasploitDataModels::AutomaticExploitation::MatchResult::SUCCEEDED)
      end
    end

    context 'failed' do
      subject(:failed) do
        described_class.failed
      end

      specify 'returns only failed results' do
        expect(failed.count).to eq(1)
        expect(failed.first.state).to eq(MetasploitDataModels::AutomaticExploitation::MatchResult::FAILED)
      end
    end
  end

  context 'validations' do
    context 'state' do
      subject(:match_result) do
        FactoryGirl.build(:automatic_exploitation_match_result, state: state)
      end
      context 'with nil' do
        let(:state) { nil }
        specify do
          expect(match_result).not_to be_valid
          expect(match_result.errors[:state]).to include("can't be blank")
        end
      end
      context 'with "asdf"' do
        let(:state) { "asdf" }
        specify do
          expect(match_result).not_to be_valid
          expect(match_result.errors[:state]).to include("is not included in the list")
        end
      end
      context 'with "succeeded"' do
        let(:state) { MetasploitDataModels::AutomaticExploitation::MatchResult::SUCCEEDED }
        specify do
          expect(match_result).to be_valid
        end
      end
    end
  end

end
