index
int64
0
0
repo_id
stringclasses
829 values
file_path
stringlengths
34
254
content
stringlengths
6
5.38M
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/divorce_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::Divorce do let(:divorce_info_v2) do { 'date' => '2020-01-01', 'ssn' => '848525794', 'birth_date' => '1990-03-03', 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }, 'divorce_location' => { 'location' => { 'state' => 'FL', 'city' => 'Tampa' } }, 'reason_marriage_ended' => 'Divorce', 'spouse_income' => 'N' } end let(:formatted_params_result) do { 'divorce_state' => 'FL', 'divorce_city' => 'Tampa', 'ssn' => '848525794', 'birth_date' => '1990-03-03', 'divorce_country' => nil, 'marriage_termination_type_code' => 'Divorce', 'end_date' => DateTime.parse("#{divorce_info_v2['date']} 12:00:00").to_time.iso8601, 'vet_ind' => 'N', 'type' => 'divorce', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.', 'spouse_income' => 'N' } end describe '#format_info' do it 'formats divorce params for submission' do formatted_info = described_class.new(divorce_info_v2).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/death_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::Death do let(:death_info_v2) do { 'deceased_dependent_income' => 'N', 'dependent_death_location' => { 'location' => { 'city' => 'portland', 'state' => 'ME' } }, 'dependent_death_date' => '2024-08-01', 'dependent_type' => 'DEPENDENT_PARENT', 'full_name' => { 'first' => 'first', 'middle' => 'middle', 'last' => 'last' }, 'ssn' => '987654321', 'birth_date' => '1960-01-01' } end let(:formatted_params_result_v2) do { 'death_date' => '2024-08-01T12:00:00+00:00', 'vet_ind' => 'N', 'ssn' => '987654321', 'birth_date' => '1960-01-01', 'first' => 'first', 'middle' => 'middle', 'last' => 'last', 'dependent_income' => 'N' } end describe '#format_info' do it 'formats death params for submission' do formatted_info = described_class.new(death_info_v2).format_info expect(formatted_info).to eq(formatted_params_result_v2) end end describe '#format_info for spouse' do it 'formats death params for submission' do formatted_info = described_class.new(death_info_v2.merge({ 'dependent_type' => 'SPOUSE' })).format_info expect(formatted_info).to eq(formatted_params_result_v2.merge({ 'marriage_termination_type_code' => 'Death' })) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/marriage_history_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::MarriageHistory do let(:marriage_history_info_v2) do { 'start_date' => '2007-04-03', 'start_location' => { 'location' => { 'state' => 'AK', 'city' => 'Rock Island' } }, 'reason_marriage_ended' => 'Other', 'other_reason_marriage_ended' => 'Some other reason', 'end_date' => '2009-05-05', 'end_location' => { 'location' => { 'state' => 'IL', 'city' => 'Chicago' } }, 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' } } end let(:formatted_params_result) do { 'start_date' => '2007-04-03', 'end_date' => '2009-05-05', 'marriage_country' => nil, 'marriage_state' => 'AK', 'marriage_city' => 'Rock Island', 'divorce_state' => 'IL', 'divorce_city' => 'Chicago', 'divorce_country' => nil, 'marriage_termination_type_code' => 'Other', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' } end describe '#format_info' do it 'formats marriage history params for submission' do formatted_info = described_class.new(marriage_history_info_v2).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/spouse_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::Spouse do let(:veteran_spouse_v2) { build(:spouse_v2) } let(:spouse_v2) { described_class.new(veteran_spouse_v2['dependents_application']) } let(:format_info_output) do { 'ssn' => '323454323', 'birth_date' => '1981-04-04', 'ever_married_ind' => 'Y', 'martl_status_type_cd' => 'Married', 'vet_ind' => 'Y', 'first' => 'Jenny', 'middle' => 'Lauren', 'last' => 'McCarthy', 'suffix' => 'Sr.', 'va_file_number' => '00000000' } end let(:address_output_v2) do { 'country' => 'USA', 'street' => '8200 Doby LN', 'city' => 'Pasadena', 'state' => 'CA', 'postal_code' => '21122' } end describe '#format_info' do it 'formats relationship params for submission' do formatted_info = spouse_v2.format_info expect(formatted_info).to include(format_info_output) end end describe '#address' do it 'returns an address for vet or spouse if separated' do address = spouse_v2.address expect(address).to eq(address_output_v2) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/adult_child_attending_school_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::AdultChildAttendingSchool do let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:adult_child_attending_school_v2) do described_class.new(all_flows_payload_v2['dependents_application']['student_information'][0]) end let(:formatted_info_response_v2) do { 'ssn' => '987654321', 'birth_date' => '2005-01-01', 'ever_married_ind' => 'Y', 'first' => 'test', 'middle' => 'middle', 'last' => 'student', 'suffix' => nil, 'dependent_income' => 'Y', 'relationship_to_student' => 'Biological' } end let(:address_response_v2) do { 'country' => 'USA', 'street' => '123 fake street', 'street2' => 'line2', 'street3' => 'line3', 'city' => 'portland', 'state' => 'ME', 'postal_code' => '04102' } end describe '#format_info' do it 'formats info' do formatted_info = adult_child_attending_school_v2.format_info expect(formatted_info).to eq(formatted_info_response_v2) end end describe '#address' do it 'formats info' do address = adult_child_attending_school_v2.address expect(address).to eq(address_response_v2) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/child_marriage_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::ChildMarriage do let(:child_marriage_info) do { 'date_married' => '1977-02-01', 'ssn' => '555612341', 'birth_date' => '2020-01-01', 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }, 'dependent_income' => 'Y' } end let(:formatted_params_result) do { 'event_date' => '1977-02-01', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.', 'ssn' => '555612341', 'birth_date' => '2020-01-01', 'ever_married_ind' => 'Y', 'dependent_income' => 'Y' } end describe '#format_info' do it 'formats child marriage params for submission' do formatted_info = described_class.new(child_marriage_info).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/step_child_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::StepChild do let(:stepchild_info_v2) do { 'supporting_stepchild' => true, 'living_expenses_paid' => 'Half', 'ssn' => '213685794', 'birth_date' => '2010-03-03', 'who_does_the_stepchild_live_with' => { 'first' => 'Adam', 'middle' => 'Steven', 'last' => 'Huberws' }, 'address' => { 'country' => 'USA', 'street' => '412 Crooks Road', 'city' => 'Clawson', 'state' => 'AL', 'postal_code' => '48017' }, 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' } } end let(:formatted_params_result) do { 'living_expenses_paid' => '.5', 'lives_with_relatd_person_ind' => 'N', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'ssn' => '213685794', 'birth_date' => '2010-03-03', 'suffix' => 'Sr.' } end describe '#format_info' do it 'formats stepchild params for submission' do formatted_info = described_class.new(stepchild_info_v2).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/child_student_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::ChildStudent do let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:child_student_info_v2) do described_class.new('3829729', '149471', all_flows_payload_v2['dependents_application']['student_information'][0]) end let(:formatted_params_result_v2) do { vnp_proc_id: '3829729', vnp_ptcpnt_id: '149471', saving_amt: '500', real_estate_amt: '300', other_asset_amt: '200', rmks: 'test additional information', marage_dt: DateTime.parse('2024-03-03 12:00:00').to_time.iso8601, agency_paying_tuitn_nm: nil, stock_bond_amt: '400', govt_paid_tuitn_ind: 'Y', govt_paid_tuitn_start_dt: DateTime.parse('2024-03-01 12:00:00').to_time.iso8601, term_year_emplmt_income_amt: '56000', term_year_other_income_amt: '20', term_year_ssa_income_amt: '0', term_year_annty_income_amt: '123', next_year_annty_income_amt: '145', next_year_emplmt_income_amt: '56000', next_year_other_income_amt: '50', next_year_ssa_income_amt: '0', acrdtdSchoolInd: 'Y', atndedSchoolCntnusInd: 'Y', stopedAtndngSchoolDt: nil } end describe '#params_for_686c' do it 'formats child student params for submission' do formatted_info = child_student_info_v2.params_for_686c expect(formatted_info).to eq(formatted_params_result_v2) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/relationship_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::Relationship do let(:event_date) { '2001/02/03' } let(:dependent) do { vnp_participant_id: '146189', participant_relationship_type_name: 'Spouse', family_relationship_type_name: 'Spouse', marriage_state: 'FL', marriage_city: 'Tampa', event_date: } end let(:params_response) do { vnp_proc_id: '1234', vnp_ptcpnt_id_a: '1234', vnp_ptcpnt_id_b: '146189', ptcpnt_rlnshp_type_nm: 'Spouse', family_rlnshp_type_nm: 'Spouse', event_dt: DateTime.parse("#{event_date} 12:00:00").to_time.iso8601 } end describe 'params for 686c' do it 'formats relationship params for submission' do expect( described_class.new('1234') .params_for_686c('1234', dependent) ).to include(params_response) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/child_school_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::ChildSchool do let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:child_school_info_v2) do described_class.new('3829729', '149471', all_flows_payload_v2['dependents_application']['student_information'][0]) end let(:formatted_params_result_v2) do { vnp_proc_id: '3829729', vnp_ptcpnt_id: '149471', last_term_start_dt: DateTime.parse('2024-01-01 12:00:00').to_time.iso8601, last_term_end_dt: DateTime.parse('2024-03-05 12:00:00').to_time.iso8601, prev_hours_per_wk_num: nil, prev_sessns_per_wk_num: nil, prev_school_nm: nil, prev_school_cntry_nm: nil, prev_school_addrs_one_txt: nil, prev_school_city_nm: nil, prev_school_postal_cd: nil, prev_school_addrs_zip_nbr: nil, curnt_school_nm: 'name of trade program', curnt_school_addrs_one_txt: nil, curnt_school_postal_cd: nil, curnt_school_city_nm: nil, curnt_school_addrs_zip_nbr: nil, curnt_school_cntry_nm: nil, course_name_txt: nil, curnt_sessns_per_wk_num: nil, curnt_hours_per_wk_num: nil, school_actual_expctd_start_dt: '2025-01-02', school_term_start_dt: DateTime.parse('2025-01-01 12:00:00').to_time.iso8601, gradtn_dt: DateTime.parse('2026-03-01 12:00:00').to_time.iso8601, full_time_studnt_type_cd: nil, part_time_school_subjct_txt: nil } end describe '#params for 686c' do it 'formats child school params for submission' do formatted_info = child_school_info_v2.params_for_686c expect(formatted_info).to include(formatted_params_result_v2) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/vnp_benefit_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::VnpBenefitClaim do let(:veteran) do { vnp_participant_id: '146189', vnp_participant_address_id: '113372', participant_claimant_id: '600061742', benefit_claim_type_end_product: '032312395' } end let(:benefit_claim) { described_class.new('3828033', veteran) } let(:create_params_output) do { vnp_proc_id: '3828033', ptcpnt_clmant_id: '146189', ptcpnt_mail_addrs_id: '113372', vnp_ptcpnt_vet_id: '146189' } end let(:update_params_output) do { vnp_proc_id: '3828033', vnp_bnft_claim_id: '425718', bnft_claim_type_cd: '130DPNEBNADJ', end_prdct_type_cd: '032312395', bnft_claim_id: '600196508', vnp_ptcpnt_vet_id: '146189', ptcpnt_clmant_id: '146189', status_type_cd: 'PEND' } end let(:vnp_benefit_claim_update_param) do { vnp_proc_id: '3828033', vnp_benefit_claim_id: '425718', vnp_benefit_claim_type_code: '130DPNEBNADJ', claim_jrsdtn_lctn_id: '335', intake_jrsdtn_lctn_id: '335', participant_claimant_id: '146189' } end let(:benefit_claim_record) do { benefit_claim_id: '600196508', claim_type_code: '130DPNEBNADJ', program_type_code: 'CPL', service_type_code: 'CP', status_type_code: 'PEND' } end let(:response_output) do { vnp_proc_id: '3828033', vnp_benefit_claim_id: '425718', vnp_benefit_claim_type_code: '130DPNEBNADJ', claim_jrsdtn_lctn_id: '335', intake_jrsdtn_lctn_id: '335', participant_claimant_id: '146189' } end let(:vnp_benefit_claim_response_param) do { vnp_bnft_claim_id: '425718', bnft_claim_type_cd: '130DPNEBNADJ', claim_jrsdtn_lctn_id: '335', intake_jrsdtn_lctn_id: '335', jrn_lctn_id: '281', jrn_obj_id: 'VAgovAPI', jrn_status_type_cd: 'U', jrn_user_id: 'VAgovAPI', pgm_type_cd: 'COMP', ptcpnt_clmant_id: '146189', vnp_ptcpnt_vet_id: '146189', vnp_proc_id: '3828033' } end describe '#create_params_for_686c' do it 'creates params for submission to BGS for 686c' do create_params = benefit_claim.create_params_for_686c expect(create_params).to include(create_params_output) end end describe '#update_params_for_686c' do it 'creates update params for submission to BGS for 686c' do update_params = benefit_claim.update_params_for_686c(vnp_benefit_claim_update_param, benefit_claim_record) expect(update_params).to include(update_params_output) end end describe '#vnp_benefit_claim_response' do it 'creates update params for submission to BGS for 686c' do response = benefit_claim.vnp_benefit_claim_response(vnp_benefit_claim_response_param) expect(response).to include(response_output) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/child_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependentsV2::Child do let(:child_info_v2) do { 'does_child_live_with_you' => true, 'income_in_last_year' => 'N', 'birth_location' => { 'location' => { 'state' => 'NH', 'city' => 'Concord', 'postal_code' => '03301' } }, 'is_biological_child' => true, 'has_child_ever_been_married' => true, 'marriage_end_date' => '2024-06-01', 'marriage_end_reason' => 'annulment', 'marriage_end_description' => 'description of annulment', 'full_name' => { 'first' => 'first', 'middle' => 'middle', 'last' => 'last' }, 'ssn' => '987654321', 'birth_date' => '2005-01-01', 'does_child_have_permanent_disability' => false } end let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:address_result_v2) do { 'country' => 'USA', 'street' => '123 fake street', 'street2' => 'test2', 'street3' => 'test3', 'city' => 'portland', 'state' => 'ME', 'postal_code' => '04102' } end let(:multiple_children_v2) { build(:dependency_claim_v2) } describe '#format_info' do let(:format_info_output) do { 'ssn' => '987654321', 'family_relationship_type' => 'Biological', 'place_of_birth_state' => 'NH', 'place_of_birth_city' => 'Concord', 'reason_marriage_ended' => 'annulment', 'ever_married_ind' => 'Y', 'birth_date' => '2005-01-01', 'place_of_birth_country' => nil, 'first' => 'first', 'middle' => 'middle', 'last' => 'last', 'suffix' => nil, 'child_income' => 'N', 'not_self_sufficient' => 'N' } end it 'formats relationship params for submission' do formatted_info = described_class.new(child_info_v2).format_info expect(formatted_info).to eq(format_info_output) end it 'handles multiple formats of child relationships' do children = multiple_children_v2.parsed_form['dependents_application']['children_to_add'].map do |child_info| described_class.new(child_info).format_info end expect(children).to match([a_hash_including('family_relationship_type' => 'Biological'), a_hash_including('family_relationship_type' => 'Stepchild'), a_hash_including('family_relationship_type' => 'Adopted Child'), a_hash_including('family_relationship_type' => 'Biological'), a_hash_including('family_relationship_type' => 'Adopted Child'), a_hash_including('family_relationship_type' => 'Biological')]) end end describe '#address' do it 'formats address' do address = described_class.new(child_info_v2).address(all_flows_payload_v2['dependents_application']) expect(address).to eq(address_result_v2) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents_v2/base_spec.rb
# frozen_string_literal: true require 'rails_helper' TEST_COUNTRIES = { 'USA' => 'USA', 'BOL' => 'Bolivia', 'BIH' => 'Bosnia-Herzegovina', 'BRN' => 'Brunei', 'CPV' => 'Cape Verde', 'COG' => "Congo, People's Republic of", 'COD' => 'Congo, Democratic Republic of', 'CIV' => "Cote d'Ivoire", 'CZE' => 'Czech Republic', 'PRK' => 'North Korea', 'KOR' => 'South Korea', 'LAO' => 'Laos', 'MKD' => 'Macedonia', 'MDA' => 'Moldavia', 'RUS' => 'Russia', 'KNA' => 'St. Kitts', 'LCA' => 'St. Lucia', 'STP' => 'Sao-Tome/Principe', 'SCG' => 'Serbia', 'SYR' => 'Syria', 'TZA' => 'Tanzania', 'GBR' => 'United Kingdom', 'VEN' => 'Venezuela', 'VNM' => 'Vietnam', 'YEM' => 'Yemen Arab Republic' }.freeze RSpec.describe BGSDependentsV2::Base do let(:base) { described_class.new } let(:sample_v2_dependent_application) do { 'veteran_contact_information' => { 'veteran_address' => { 'country' => 'USA', 'street' => '8200 Doby LN', 'street2' => 'test line two', 'street3' => 'test line 3', 'city' => 'Pasadena', 'state' => 'CA', 'postal_code' => '21122' } } } end let(:alternative_address) do { 'country_name' => 'USA', 'address_line1' => 'Alternative LN', 'city' => 'Stuart', 'state_code' => 'FL', 'zip_code' => '21122' } end describe '#dependent_address' do it 'returns the vet\'s address' do address = base.dependent_address( dependents_application: sample_v2_dependent_application, lives_with_vet: true, alt_address: nil ) expect(address).to eq(sample_v2_dependent_application['veteran_contact_information']['veteran_address']) end it 'returns the alternative address' do address = base.dependent_address( dependents_application: sample_v2_dependent_application, lives_with_vet: false, alt_address: alternative_address ) expect(address).to eq(alternative_address) end context 'it is a foreign address' do TEST_COUNTRIES.each do |abbreviation, bis_value| it "returns #{bis_value} when it gets #{abbreviation} as the country" do address = sample_v2_dependent_application['veteran_contact_information']['veteran_address'] address['country'] = abbreviation address['international_postal_code'] = '12345' base.adjust_country_name_for!(address:) expect(address['country']).to eq(bis_value) end end it 'tests TUR when the city is Adana' do address = sample_v2_dependent_application['veteran_contact_information']['veteran_address'] address['country'] = 'TUR' address['international_postal_code'] = '12345' address['city'] = 'Adana' base.adjust_country_name_for!(address:) expect(address['country']).to eq('Turkey (Adana only)') end it 'tests TUR when the city is not Adana' do address = sample_v2_dependent_application['veteran_contact_information']['veteran_address'] address['country'] = 'TUR' address['international_postal_code'] = '12345' address['city'] = 'Istanbul' base.adjust_country_name_for!(address:) expect(address['country']).to eq('Turkey (except Adana)') end it 'tests a country outside of the hash' do address = sample_v2_dependent_application['veteran_contact_information']['veteran_address'] address['country'] = 'ITA' address['international_postal_code'] = '12345' base.adjust_country_name_for!(address:) expect(address['country']).to eq('Italy') end it 'receives nil for state in the address' do address = sample_v2_dependent_application['veteran_contact_information']['veteran_address'] address['country'] = 'ITA' address['international_postal_code'] = '12345' address['state'] = 'Tuscany' params = base.create_address_params('1', '1', address) expect(params[:postal_cd]).to be_nil expect(params[:prvnc_nm]).to eq('Tuscany') expect(params[:zip_prefix_nbr]).to be_nil end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/persistent_attachments/dependency_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe PersistentAttachments::DependencyClaim, :uploader_helpers do let(:file) { Rails.root.join('spec', 'fixtures', 'files', 'marriage-certificate.pdf') } let(:instance) { described_class.new(form_id: '686C-674') } before do allow(Common::VirusScan).to receive(:scan).and_return(true) end it 'sets a guid on initialize' do expect(instance.guid).to be_a(String) end it 'allows adding a file' do allow_any_instance_of(ClamAV::PatchClient).to receive(:safe?).and_return(true) instance.file = file.open expect(instance.valid?).to be(true) expect(instance.file.shrine_class).to be(ClaimDocumentation::Uploader) end context 'stamp_text', run_at: '2017-08-01 01:01:00 EDT' do it 'offsets a user timestamp by their browser data' do instance.saved_claim = create( :dependency_claim ) expect(instance.send(:stamp_text)).to eq('2017-08-01') end end describe '#delete_file' do stub_virus_scan it 'deletes the file after destroying the model' do instance.file = file.open instance.save! shrine_file = instance.file expect(shrine_file.exists?).to be(true) instance.destroy expect(shrine_file.exists?).to be(false) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/persistent_attachments/lgy_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe PersistentAttachments::LgyClaim, :uploader_helpers do let(:file) { Rails.root.join('spec', 'fixtures', 'files', 'marriage-certificate.pdf') } let(:instance) { described_class.new(form_id: '28-1880') } before do allow(Common::VirusScan).to receive(:scan).and_return(true) end it 'sets a guid on initialize' do expect(instance.guid).to be_a(String) end it 'allows adding a file' do allow_any_instance_of(ClamAV::PatchClient).to receive(:safe?).and_return(true) instance.file = file.open expect(instance.valid?).to be(true) expect(instance.file.shrine_class).to be(ClaimDocumentation::Uploader) end context 'stamp_text', run_at: '2017-08-01 01:01:00 EDT' do it 'offsets a user timestamp by their browser data' do instance.saved_claim = create( :dependency_claim ) expect(instance.send(:stamp_text)).to eq('2017-08-01') end end describe '#delete_file' do stub_virus_scan it 'deletes the file after destroying the model' do instance.file = file.open instance.save! shrine_file = instance.file expect(shrine_file.exists?).to be(true) instance.destroy expect(shrine_file.exists?).to be(false) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/persistent_attachments/va_form_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe PersistentAttachments::VAForm, :uploader_helpers do let(:file) { Rails.root.join('spec', 'fixtures', 'files', 'marriage-certificate.pdf') } let(:instance) { described_class.new } before do allow(Common::VirusScan).to receive(:scan).and_return(true) end it 'sets a guid on initialize' do expect(instance.guid).to be_a(String) end it 'allows adding a file' do allow_any_instance_of(ClamAV::PatchClient).to receive(:safe?).and_return(true) instance.file = file.open expect(instance.valid?).to be(true) expect(instance.file.shrine_class).to be(FormUpload::Uploader) end describe '#max_pages' do context 'form_id 21-0779' do before { instance.form_id = '21-0779' } it 'returns 4' do expect(instance.max_pages).to eq 4 end end context 'form_id 21-509' do before { instance.form_id = '21-509' } it 'returns 4' do expect(instance.max_pages).to eq 4 end end context 'form_id 21-686c' do before { instance.form_id = '21-686c' } it 'returns 16' do expect(instance.max_pages).to eq 16 end end context 'form_id 21P-0518-1' do before { instance.form_id = '21P-0518-1' } it 'returns 2' do expect(instance.max_pages).to eq 2 end end context 'form_id 21P-0516-1' do before { instance.form_id = '21P-0516-1' } it 'returns 2' do expect(instance.max_pages).to eq 2 end end context 'form_id 21P-530a' do before { instance.form_id = '21P-530a' } it 'returns 2' do expect(instance.max_pages).to eq 2 end end context 'form_id 21P-8049' do before { instance.form_id = '21P-8049' } it 'returns 4' do expect(instance.max_pages).to eq 4 end end context 'default' do it 'returns 10' do expect(instance.max_pages).to eq 10 end end end describe '#min_pages' do context 'form_id 21-0779' do before { instance.form_id = '21-0779' } it 'returns 2' do expect(instance.min_pages).to eq 2 end end context 'form_id 21-509' do before { instance.form_id = '21-509' } it 'returns 2' do expect(instance.min_pages).to eq 2 end end context 'form_id 21P-0518-1' do before { instance.form_id = '21P-0518-1' } it 'returns 2' do expect(instance.min_pages).to eq 2 end end context 'form_id 21P-0516-1' do before { instance.form_id = '21P-0516-1' } it 'returns 2' do expect(instance.min_pages).to eq 2 end end context 'form_id 21-686c' do before { instance.form_id = '21-686c' } it 'returns 2' do expect(instance.min_pages).to eq 2 end end context 'default' do it 'returns 1' do expect(instance.min_pages).to eq 1 end end end describe '#delete_file' do stub_virus_scan it 'deletes the file after destroying the model' do instance.file = file.open instance.save! shrine_file = instance.file expect(shrine_file.exists?).to be(true) instance.destroy expect(shrine_file.exists?).to be(false) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/persistent_attachments/claim_evidence_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe PersistentAttachments::ClaimEvidence, :uploader_helpers do let(:file) { Rails.root.join('spec', 'fixtures', 'files', 'marriage-certificate.pdf') } let(:instance) { described_class.new(form_id: '28-1880') } before do allow(Common::VirusScan).to receive(:scan).and_return(true) end it 'sets a guid on initialize' do expect(instance.guid).to be_a(String) end it 'allows adding a file' do allow_any_instance_of(ClamAV::PatchClient).to receive(:safe?).and_return(true) instance.file = file.open expect(instance.valid?).to be(true) expect(instance.file.shrine_class).to be(ClaimDocumentation::Uploader) end context 'stamp_text', run_at: '2017-08-01 01:01:00 EDT' do it 'offsets a user timestamp by their browser data' do instance.saved_claim = create( :fake_saved_claim ) expect(instance.send(:stamp_text)).to eq('2017-08-01') end end describe '#delete_file' do stub_virus_scan it 'deletes the file after destroying the model' do instance.file = file.open instance.save! shrine_file = instance.file expect(shrine_file.exists?).to be(true) instance.destroy expect(shrine_file.exists?).to be(false) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/session_container_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::SessionContainer, type: :model do let(:session_container) do create(:session_container, session:, refresh_token:, access_token:, anti_csrf_token:, client_config:, device_secret:) end let(:session) { create(:oauth_session) } let(:refresh_token) { create(:refresh_token) } let(:access_token) { create(:access_token) } let(:anti_csrf_token) { SecureRandom.hex } let(:device_secret) { SecureRandom.hex } let(:client_config) { create(:client_config) } describe 'validations' do describe '#session' do subject { session_container.session } context 'when session is nil' do let(:session) { nil } let(:expected_error_message) { "Validation failed: Session can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#refresh_token' do subject { session_container.refresh_token } context 'when refresh_token is nil' do let(:refresh_token) { nil } let(:expected_error_message) { "Validation failed: Refresh token can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token' do subject { session_container.access_token } context 'when access_token is nil' do let(:access_token) { nil } let(:expected_error_message) { "Validation failed: Access token can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#anti_csrf_token' do subject { session_container.anti_csrf_token } context 'when anti_csrf_token is nil' do let(:anti_csrf_token) { nil } let(:expected_error_message) { "Validation failed: Anti csrf token can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#client_config' do subject { session_container.client_config } context 'when client_config is nil' do let(:client_config) { nil } let(:expected_error_message) { "Validation failed: Client config can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end describe '#context' do subject { session_container.context } let(:expected_context) do { user_uuid: session_container.access_token.user_uuid, session_handle: session_container.session.handle, client_id: session_container.session.client_id, type: session.user_verification.credential_type, icn: session.user_account.icn } end it 'returns serialized access_token context details' do expect(subject).to eq(expected_context) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/certificate_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::Certificate, type: :model do subject(:certificate) { build(:sign_in_certificate) } describe 'associations' do it { is_expected.to have_many(:config_certificates).dependent(:destroy) } it { is_expected.to have_many(:client_configs).through(:config_certificates) } it { is_expected.to have_many(:service_account_configs).through(:config_certificates) } end describe 'scopes' do describe '.active' do let!(:active_certificate) { create(:sign_in_certificate) } let!(:expiring_soon_certificate) { create(:sign_in_certificate, :expiring_soon) } let(:expired_certificate) { build(:sign_in_certificate, :expired) } before do expired_certificate.save(validate: false) end it 'returns only active certificates' do expect(SignIn::Certificate.active).to include(active_certificate) end it 'returns expiring soon certificates' do expect(SignIn::Certificate.active).to include(expiring_soon_certificate) end end describe '.expired' do let(:expired_certificate) { build(:sign_in_certificate, :expired) } let(:not_expired_certificate) { create(:sign_in_certificate) } before do expired_certificate.save(validate: false) end it 'returns only expired certificates' do expect(SignIn::Certificate.expired).to contain_exactly(expired_certificate) end end describe '.expiring_soon' do let!(:expiring_soon_certificate) { create(:sign_in_certificate, :expiring_soon) } let!(:not_expiring_certificate) { create(:sign_in_certificate, not_before: 61.days.ago) } it 'returns only certificates expiring within 60 days' do expect(SignIn::Certificate.expiring_soon).to contain_exactly(expiring_soon_certificate) end end end describe 'validations' do it { is_expected.to validate_presence_of(:pem) } context 'when PEM is invalid' do subject(:certificate) { build(:sign_in_certificate, pem: 'not a valid pem') } it 'is not valid and adds X.509 error' do expect(certificate).not_to be_valid expect(certificate.errors[:pem]).to include('not a valid X.509 certificate') end end context 'when certificate is valid' do it { is_expected.to be_valid } end context 'when the certificate is expired' do subject(:certificate) { build(:sign_in_certificate, :expired) } it 'is not valid and adds expired error' do expect(certificate).not_to be_valid expect(certificate.errors[:pem]).to include('X.509 certificate is expired') end it '#expired? returns true' do expect(certificate.expired?).to be true end end context 'when the certificate is not yet valid' do subject(:certificate) { build(:sign_in_certificate, :not_yet_valid) } it 'is not valid and adds “not yet valid” error' do expect(certificate).not_to be_valid expect(certificate.errors[:pem]).to include('X.509 certificate is not yet valid') end end context 'when the certificate is self-signed' do subject(:certificate) { build(:sign_in_certificate, :self_signed) } it 'is not valid and adds self‑signed error' do expect(certificate).not_to be_valid expect(certificate.errors[:pem]).to include('X.509 certificate is self-signed') end end end describe 'delegations' do it { is_expected.to delegate_method(:not_before).to(:x509) } it { is_expected.to delegate_method(:not_after).to(:x509) } it { is_expected.to delegate_method(:subject).to(:x509) } it { is_expected.to delegate_method(:issuer).to(:x509) } it { is_expected.to delegate_method(:serial).to(:x509) } end describe '#certificate' do context 'when PEM is valid' do it 'returns an OpenSSL::X509::Certificate object' do expect(certificate.x509).to be_a(OpenSSL::X509::Certificate) end end context 'when PEM is invalid' do subject(:certificate) { build(:sign_in_certificate, pem: 'not a valid pem') } it 'returns nil' do expect(certificate.x509).to be_nil end end end describe '#certificate?' do context 'when certificate is valid' do it 'returns true' do expect(certificate.x509?).to be true end end context 'when certificate is invalid' do subject(:certificate) { build(:sign_in_certificate, pem: 'not a valid pem') } it 'returns false' do expect(certificate.x509?).to be false end end end describe '#status' do context 'when certificate is active' do subject(:certificate) { build(:sign_in_certificate) } it 'returns "active"' do expect(certificate.status).to eq('active') end end context 'when certificate is expired' do subject(:certificate) { build(:sign_in_certificate, :expired) } it 'returns "expired"' do expect(certificate.status).to eq('expired') end end context 'when certificate is expiring' do subject(:certificate) { build(:sign_in_certificate, :expiring_soon) } it 'returns "expiring"' do expect(certificate.status).to eq('expiring_soon') end end end describe '#public_key' do context 'when certificate is valid' do it 'returns the public key of the certificate' do expect(certificate.public_key).to be_a(OpenSSL::PKey::RSA) end end context 'when certificate is invalid' do subject(:certificate) { build(:sign_in_certificate, pem: 'not a valid pem') } it 'returns nil' do expect(certificate.public_key).to be_nil end end end describe '#active?' do context 'when the certificate is active' do subject(:certificate) { build(:sign_in_certificate) } it 'returns true' do expect(certificate.active?).to be true end context 'when the certificate is expired' do subject(:certificate) { build(:sign_in_certificate, :expired) } it 'returns false' do expect(certificate.active?).to be false end end end end describe '#expired?' do context 'when the certificate is expired' do subject(:certificate) { build(:sign_in_certificate, :expired) } it 'returns true' do expect(certificate.expired?).to be true end context 'when the certificate is not expired' do subject(:certificate) { build(:sign_in_certificate) } it 'returns false' do expect(certificate.expired?).to be false end end end end describe '#expiring_soon?' do context 'when the certificate is expiring within 60 days' do subject(:certificate) { build(:sign_in_certificate, :expiring_soon) } it 'returns true' do expect(certificate.expiring_soon?).to be true end context 'when the certificate is not expiring' do subject(:certificate) { build(:sign_in_certificate) } it 'returns false' do expect(certificate.expiring_soon?).to be false end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/validated_credential_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::ValidatedCredential, type: :model do let(:validated_credential) do create(:validated_credential, user_verification:, credential_email:, client_config:, user_attributes:, device_sso:) end let(:user_verification) { create(:user_verification) } let(:credential_email) { 'some-credential-email' } let(:client_config) { create(:client_config) } let(:user_attributes) do { first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email } end let(:device_sso) { false } describe 'validations' do describe '#user_verification' do subject { validated_credential.user_verification } context 'when user_verification is nil' do let(:user_verification) { nil } let(:expected_error_message) { "Validation failed: User verification can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when client_config is nil' do let(:client_config) { nil } let(:expected_error_message) { "Validation failed: Client config can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/config_certificate_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::ConfigCertificate, type: :model do subject(:config_certificate) { create(:sign_in_config_certificate) } describe 'associations' do it { is_expected.to belong_to(:cert) } it { is_expected.to belong_to(:config) } end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/user_code_map_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::UserCodeMap, type: :model do let(:user_code_map) do create(:user_code_map, login_code:, type:, client_state:, client_config:, terms_code:) end let(:login_code) { 'some-login-code' } let(:type) { 'some-type' } let(:client_state) { 'some-client-state' } let(:client_config) { create(:client_config) } let(:terms_code) { 'some-terms-code' } describe 'validations' do describe '#login_code' do subject { user_code_map.login_code } context 'when login_code is nil' do let(:login_code) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Login code can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when type is nil' do let(:type) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Type can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when client_config is nil' do let(:client_config) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Client config can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/code_container_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::CodeContainer, type: :model do let(:code_container) do create(:code_container, code_challenge:, client_id:, code:, user_verification_id:, user_attributes:, device_sso:, web_sso_session_id:) end let(:code_challenge) { Base64.urlsafe_encode64(SecureRandom.hex) } let(:code) { SecureRandom.hex } let(:client_config) { create(:client_config) } let(:client_id) { client_config.client_id } let(:user_verification_id) { create(:user_verification).id } let(:user_attributes) do { first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email } end let(:device_sso) { false } let(:web_sso_session_id) { nil } describe 'validations' do describe '#code' do subject { code_container.code } context 'when code is nil' do let(:code) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#user_verification_id' do subject { code_container.user_verification_id } context 'when user_verification_id is nil' do let(:user_verification_id) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#client_id' do subject { code_container.client_id } context 'when client_id is nil' do let(:client_id) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when client_id is an arbitrary value' do let(:client_id) { 'some-client-id' } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/o_auth_session_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::OAuthSession, type: :model do let(:oauth_session) do create(:oauth_session, user_verification:, handle:, hashed_refresh_token:, refresh_expiration:, refresh_creation:, client_id:, user_attributes:) end let(:user_verification) { create(:user_verification) } let(:handle) { SecureRandom.hex } let(:hashed_refresh_token) { SecureRandom.hex } let(:refresh_expiration) { Time.zone.now + 1000 } let(:refresh_creation) { Time.zone.now } let(:client_config) { create(:client_config) } let(:client_id) { client_config.client_id } let(:user_attributes) { { first_name:, last_name:, email: }.to_json } let(:first_name) { Faker::Name.first_name } let(:last_name) { Faker::Name.last_name } let(:email) { Faker::Internet.email } describe 'validations' do describe '#user_verification' do subject { oauth_session.user_verification } context 'when user_verification is nil' do let(:user_verification) { nil } let(:expected_error_message) { 'Validation failed: User verification must exist' } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end describe '#handle' do subject { oauth_session.handle } context 'when handle is nil' do let(:handle) { nil } let(:expected_error_message) { "Validation failed: Handle can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end context 'when handle is duplicate' do let!(:oauth_session_dup) { create(:oauth_session, handle:) } let(:expected_error_message) { 'Validation failed: Handle has already been taken' } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end describe '#hashed_refresh_token' do subject { oauth_session.hashed_refresh_token } context 'when hashed_refresh_token is nil' do let(:hashed_refresh_token) { nil } let(:expected_error_message) { "Validation failed: Hashed refresh token can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end context 'when hashed_refresh_token is duplicate' do let!(:oauth_session_dup) { create(:oauth_session, hashed_refresh_token:) } let(:expected_error_message) { 'Validation failed: Hashed refresh token has already been taken' } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end describe '#refresh_expiration' do subject { oauth_session.refresh_expiration } context 'when refresh_expiration is nil' do let(:refresh_expiration) { nil } let(:expected_error_message) { "Validation failed: Refresh expiration can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end describe '#refresh_creation' do subject { oauth_session.refresh_creation } context 'when refresh_creation is nil' do let(:refresh_creation) { nil } let(:expected_error_message) { "Validation failed: Refresh creation can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end describe '#client_id' do subject { oauth_session.client_id } context 'when client_id is nil' do let(:client_id) { nil } let(:expected_error_message) { 'Validation failed: Client id must map to a configuration' } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end context 'when client_id is arbitrary' do let(:client_id) { 'some-client-id' } let(:expected_error_message) { 'Validation failed: Client id must map to a configuration' } it 'raises validation error' do expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message) end end end end describe '#active?' do subject { oauth_session.active? } let(:current_time) { Time.zone.now } context 'when current time is before refresh_expiration' do let(:refresh_expiration) { current_time + 1000 } context 'and current time is before SESSION_MAX_VALIDITY_LENGTH_DAYS days from refresh_creation' do let(:refresh_creation) { current_time } it 'returns true' do expect(subject).to be true end end context 'and current time is after SESSION_MAX_VALIDITY_LENGTH_DAYS days from refresh_creation' do let(:refresh_creation) do current_time - SignIn::Constants::RefreshToken::SESSION_MAX_VALIDITY_LENGTH_DAYS - 1.day end it 'returns false' do expect(subject).to be false end end context 'and current time is equal to SESSION_MAX_VALIDITY_LENGTH_DAYS days from refresh_creation' do let(:refresh_creation) { current_time - SignIn::Constants::RefreshToken::SESSION_MAX_VALIDITY_LENGTH_DAYS } it 'returns false' do expect(subject).to be false end end end context 'when current time is after refresh_expiration' do let(:refresh_expiration) { current_time - 1000 } it 'returns false' do expect(subject).to be false end end context 'when current time is equal to refresh_expiration' do let(:refresh_expiration) { current_time } it 'returns false' do expect(subject).to be false end end end describe '#user_attributes_hash' do subject { oauth_session.user_attributes_hash } context 'when user attributes are present' do let(:user_attributes) { { first_name:, last_name:, email: }.to_json } it 'returns a Ruby hash of the saved user_attributes' do expect(subject['first_name']).to eq(first_name) expect(subject['last_name']).to eq(last_name) expect(subject['email']).to eq(email) end end context 'when user attributes are not present' do let(:user_attributes) { nil } it 'returns an empty hash' do expect(subject).to eq({}) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/state_code_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::StateCode, type: :model do let(:state_code) { create(:state_code, code:) } let(:code) { SecureRandom.hex } describe 'validations' do describe '#code' do subject { state_code.code } context 'when code is nil' do let(:code) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/client_config_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::ClientConfig, type: :model do let(:client_config) do create(:client_config, client_id:, authentication:, shared_sessions:, anti_csrf:, redirect_uri:, logout_redirect_uri:, access_token_duration:, access_token_audience:, refresh_token_duration:, access_token_attributes:, enforced_terms:, terms_of_use_url:, service_levels:, json_api_compatibility:, credential_service_providers:) end let(:client_id) { 'some-client-id' } let(:authentication) { SignIn::Constants::Auth::API } let(:anti_csrf) { false } let(:shared_sessions) { false } let(:json_api_compatibility) { false } let(:redirect_uri) { 'some-redirect-uri' } let(:logout_redirect_uri) { 'some-logout-redirect-uri' } let(:access_token_duration) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_SHORT_MINUTES } let(:access_token_audience) { 'some-access-token-audience' } let(:refresh_token_duration) { SignIn::Constants::RefreshToken::VALIDITY_LENGTH_SHORT_MINUTES } let(:access_token_attributes) { [] } let(:enforced_terms) { SignIn::Constants::Auth::VA_TERMS } let(:terms_of_use_url) { 'some-terms-of-use-url' } let(:service_levels) { %w[loa1 loa3 ial1 ial2 min] } let(:credential_service_providers) { %w[idme logingov dslogon mhv] } describe 'associations' do it { is_expected.to have_many(:config_certificates).dependent(:destroy) } it { is_expected.to have_many(:certs).through(:config_certificates).class_name('SignIn::Certificate') } end describe 'validations' do subject { client_config } describe '#client_id' do context 'when client_id is nil' do let(:client_id) { nil } let(:expected_error_message) { "Validation failed: Client can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when client_id is not unique' do let!(:old_client_config) { create(:client_config) } let(:client_id) { old_client_config.client_id } let(:expected_error_message) { 'Validation failed: Client has already been taken' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#authentication' do context 'when authentication is nil' do let(:authentication) { nil } let(:expected_error_message) do "Validation failed: Authentication can't be blank, Authentication is not included in the list" end let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when authentication is arbitrary' do let(:authentication) { 'some-authentication' } let(:expected_error_message) { 'Validation failed: Authentication is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#refresh_token_duration' do context 'when refresh_token_duration is nil' do let(:refresh_token_duration) { nil } let(:expected_error_message) do "Validation failed: Refresh token duration can't be blank, Refresh token duration is not included in the list" end let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when refresh_token_duration is an arbitrary interval' do let(:refresh_token_duration) { 300.days } let(:expected_error_message) { 'Validation failed: Refresh token duration is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token_duration' do context 'when access_token_duration is nil' do let(:access_token_duration) { nil } let(:expected_error_message) do "Validation failed: Access token duration can't be blank, Access token duration is not included in the list" end let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when access_token_duration is an arbitrary interval' do let(:access_token_duration) { 300.days } let(:expected_error_message) { 'Validation failed: Access token duration is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#redirect_uri' do context 'when redirect_uri is nil' do let(:redirect_uri) { nil } let(:expected_error_message) { "Validation failed: Redirect uri can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#logout_redirect_uri' do context 'when logout_redirect_uri is nil' do let(:logout_redirect_uri) { nil } context 'and authentication is set to cookie auth' do let(:authentication) { SignIn::Constants::Auth::COOKIE } let(:expected_error_message) { "Validation failed: Logout redirect uri can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'and authentication is set to api auth' do let(:authentication) { SignIn::Constants::Auth::API } it 'does not raise validation error' do expect { subject }.not_to raise_error end end end end describe '#anti_csrf' do context 'when anti_csrf is nil' do let(:anti_csrf) { nil } let(:expected_error_message) { 'Validation failed: Anti csrf is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#json_api_compatibility' do context 'when json_api_compatibility is nil' do let(:json_api_compatibility) { nil } let(:expected_error_message) { 'Validation failed: Json api compatibility is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#shared_sessions' do context 'when shared_sessions is nil' do let(:shared_sessions) { nil } let(:expected_error_message) { 'Validation failed: Shared sessions is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token_attributes' do context 'when access_token_attributes is empty' do it 'does not raise a validation error' do expect { subject }.not_to raise_error end end context 'when access_token_attributes contain attributes not included in USER_ATTRIBUTES constant' do let(:access_token_attributes) { %w[first_name last_name bad_attribute] } let(:expected_error_message) { 'Validation failed: Access token attributes is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises a validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when all access_token_attributes are included in USER_ATTRIBUTES constant' do let(:access_token_attributes) { SignIn::Constants::AccessToken::USER_ATTRIBUTES } it 'does not raise a validation error' do expect { subject }.not_to raise_error end end end describe '#credential_service_providers' do context 'when credential_service_providers is empty' do let(:credential_service_providers) { [] } let(:expected_error_message) { "Validation failed: Credential service providers can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when credential_service_providers contain values not included in CSP_TYPES constant' do let(:credential_service_providers) { %w[idme logingov dslogon mhv bad_csp] } let(:expected_error_message) { 'Validation failed: Credential service providers is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when all credential_service_providers values are included in CSP_TYPES constant' do let(:credential_service_providers) { SignIn::Constants::Auth::CSP_TYPES } it 'does not raise validation error' do expect { subject }.not_to raise_error end end end describe '#service_levels' do context 'when service_levels is empty' do let(:service_levels) { [] } let(:expected_error_message) { "Validation failed: Service levels can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when service_levels contain values not included in ACR_VALUES constant' do let(:service_levels) { %w[loa1 loa3 ial1 ial2 min bad_acr] } let(:expected_error_message) { 'Validation failed: Service levels is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when all service_levels values are included in ACR_VALUES constant' do let(:service_levels) { SignIn::Constants::Auth::ACR_VALUES } it 'does not raise validation error' do expect { subject }.not_to raise_error end end end describe '#enforced_terms' do context 'when enforced_terms is arbitrary' do let(:enforced_terms) { 'some-enforced-terms' } let(:expected_error_message) { 'Validation failed: Enforced terms is not included in the list' } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#terms_of_use_url' do context 'when enforced_terms is nil' do let(:enforced_terms) { nil } context 'and terms_of_use_url is nil' do let(:terms_of_use_url) { nil } let(:expected_error_message) { "Validation failed: Terms of use url can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'does not raise validation error' do expect { subject }.not_to raise_error end end end context 'when enforced_terms is not nil' do let(:enforced_terms) { SignIn::Constants::Auth::VA_TERMS } context 'and terms_of_use_url is nil' do let(:terms_of_use_url) { nil } let(:expected_error_message) { "Validation failed: Terms of use url can't be blank" } let(:expected_error) { ActiveRecord::RecordInvalid } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'and terms_of_use_url is not nil' do let(:terms_of_use_url) { 'some-terms-of-use-url' } it 'does not raise validation error' do expect { subject }.not_to raise_error end end end end end describe '.valid_client_id?' do subject { SignIn::ClientConfig.valid_client_id?(client_id: check_client_id) } context 'when client_id matches a ClientConfig entry' do let(:check_client_id) { client_config.client_id } it 'returns true' do expect(subject).to be(true) end end context 'when client_id does not match a ClientConfig entry' do let(:check_client_id) { 'some-client-id' } it 'returns false' do expect(subject).to be(false) end end end describe '#cookie_auth?' do subject { client_config.cookie_auth? } context 'when authentication method is set to cookie' do let(:authentication) { SignIn::Constants::Auth::COOKIE } it 'returns true' do expect(subject).to be(true) end end context 'when authentication method is set to api' do let(:authentication) { SignIn::Constants::Auth::API } it 'returns false' do expect(subject).to be(false) end end context 'when authentication method is set to mock' do let(:authentication) { SignIn::Constants::Auth::MOCK } it 'returns false' do expect(subject).to be(false) end end end describe '#api_auth?' do subject { client_config.api_auth? } context 'when authentication method is set to cookie' do let(:authentication) { SignIn::Constants::Auth::COOKIE } it 'returns false' do expect(subject).to be(false) end end context 'when authentication method is set to api' do let(:authentication) { SignIn::Constants::Auth::API } it 'returns true' do expect(subject).to be(true) end end context 'when authentication method is set to mock' do let(:authentication) { SignIn::Constants::Auth::MOCK } it 'returns false' do expect(subject).to be(false) end end end describe '#va_terms_enforced?' do subject { client_config.va_terms_enforced? } context 'when enforced terms is set to VA TERMS' do let(:enforced_terms) { SignIn::Constants::Auth::VA_TERMS } it 'returns true' do expect(subject).to be(true) end end context 'when enforced terms is nil' do let(:enforced_terms) { nil } it 'returns false' do expect(subject).to be(false) end end end describe '#valid_credential_service_provider?' do subject { client_config.valid_credential_service_provider?(type) } context 'when type is included in csps' do let(:type) { 'idme' } it 'returns true' do expect(subject).to be(true) end end context 'when type is not included in csps' do let(:type) { 'bad_csp' } it 'returns false' do expect(subject).to be(false) end end end describe '#valid_service_level?' do subject { client_config.valid_service_level?(acr) } context 'when acr is included in acrs' do let(:acr) { 'loa1' } it 'returns true' do expect(subject).to be(true) end end context 'when acr is not included in acrs' do let(:acr) { 'bad_acr' } it 'returns false' do expect(subject).to be(false) end end end describe '#mock_auth?' do subject { client_config.mock_auth? } context 'when authentication method is set to mock' do let(:authentication) { SignIn::Constants::Auth::MOCK } before { allow(Settings).to receive(:vsp_environment).and_return(vsp_environment) } context 'and vsp_environment is set to test' do let(:vsp_environment) { 'test' } it 'returns true' do expect(subject).to be(true) end end context 'and vsp_environment is set to localhost' do let(:vsp_environment) { 'localhost' } it 'returns true' do expect(subject).to be(true) end end context 'and vsp_environment is set to development' do let(:vsp_environment) { 'development' } it 'returns true' do expect(subject).to be(true) end end context 'and vsp_environment is set to production' do let(:vsp_environment) { 'production' } it 'returns false' do expect(subject).to be(false) end end end context 'when authentication method is set to api' do let(:authentication) { SignIn::Constants::Auth::API } it 'returns false' do expect(subject).to be(false) end end context 'when authentication method is set to cookie' do let(:authentication) { SignIn::Constants::Auth::COOKIE } it 'returns false' do expect(subject).to be(false) end end end describe '#api_sso_enabled?' do subject { client_config.api_sso_enabled? } context 'when authentication method is set to API' do let(:authentication) { SignIn::Constants::Auth::API } context 'and shared_sessions is set to true' do let(:shared_sessions) { true } it 'returns true' do expect(subject).to be(true) end end context 'and shared_sessions is set to false' do let(:shared_sessions) { false } it 'returns false' do expect(subject).to be(false) end end end context 'when authentication method is set to COOKIE' do let(:authentication) { SignIn::Constants::Auth::COOKIE } it 'returns false' do expect(subject).to be(false) end end context 'when authentication method is set to MOCK' do let(:authentication) { SignIn::Constants::Auth::MOCK } it 'returns false' do expect(subject).to be(false) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/user_info_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::UserInfo do shared_examples 'valid GCID code' do let(:gcids) { example_gcid } it 'is valid' do expect(user_info).to be_valid end end describe 'attributes' do subject(:user_info) { described_class.new(attributes) } let(:attributes) do { sub: 'some-sub', ial: 'some-ial', aal: 'some-aal', csp_type: 'some-csp-type', csp_uuid: 'some-csp-uuid', email: 'some-email', full_name: 'some-full-name', birth_date: 'some-birth-date', ssn: 'some-ssn', gender: 'some-gender', address_street1: 'some-street1', address_street2: 'some-street2', address_city: 'some-city', address_state: 'some-state', address_country: 'some-country', address_postal_code: 'some-postal-code', phone_number: 'some-phone-number', person_types: 'some-person-types', icn: 'some-icn', sec_id: 'some-sec', edipi: 'some-edipi', mhv_ien: 'some-mhv-ien', npi_id: 'some-npi-id', cerner_id: 'some-cerner-id', corp_id: 'some-corp-id', birls: 'some-birls', gcids: } end context 'validations' do subject(:user_info) { described_class.new(attributes) } let(:attributes) do { gcids: } end context 'when gcids are valid' do let(:gcids) do '1000123456V123456^NI^200M^USVHA^P|12345^PI^516^USVHA^PCE|2^PI^553^USVHA^PCE' end it 'is valid' do expect(user_info).to be_valid end end context 'when gcids contain each valid GCID type code' do context 'ICN code' do let(:example_gcid) { '1000123456V123456^NI^200M^USVHA^P' } it_behaves_like 'valid GCID code' end context 'SEC ID code' do let(:example_gcid) { '12345^PI^200PROV^USVHA^P' } it_behaves_like 'valid GCID code' end context 'EDIPI code' do let(:example_gcid) { '1234567890^NI^200DOD^USDOD^P' } it_behaves_like 'valid GCID code' end context 'MHV IEN code' do let(:example_gcid) { '12345^PI^200MHV^USVHA^P' } it_behaves_like 'valid GCID code' end context 'NPI ID code' do let(:example_gcid) { '1234567890^NI^200ENPI^USVHA^P' } it_behaves_like 'valid GCID code' end context 'VHIC ID code' do let(:example_gcid) { '12345^PI^200VHIC^USVHA^P' } it_behaves_like 'valid GCID code' end context 'NWHIN ID code' do let(:example_gcid) { '12345^PI^200NWS^USVHA^P' } it_behaves_like 'valid GCID code' end context 'Cerner ID code' do let(:example_gcid) { '12345^PI^200CRNR^USVHA^P' } it_behaves_like 'valid GCID code' end context 'Corp ID code' do let(:example_gcid) { '12345^PI^200CORP^USVHA^P' } it_behaves_like 'valid GCID code' end context 'BIRLS ID code' do let(:example_gcid) { '12345^PI^200BRLS^USVHA^P' } it_behaves_like 'valid GCID code' end context 'Salesforce ID code' do let(:example_gcid) { '12345^PI^200DSLF^USVHA^P' } it_behaves_like 'valid GCID code' end context 'USAccess PIV code' do let(:example_gcid) { '12345^PI^200PUSA^USVHA^P' } it_behaves_like 'valid GCID code' end context 'PIV ID code' do let(:example_gcid) { '12345^PI^200PIV^USVHA^P' } it_behaves_like 'valid GCID code' end context 'VA Active Directory ID code' do let(:example_gcid) { '12345^PI^200AD^USVHA^P' } it_behaves_like 'valid GCID code' end context 'USA Staff ID code' do let(:example_gcid) { '12345^PI^200USAF^USVHA^P' } it_behaves_like 'valid GCID code' end describe 'numeric GCID codes' do let(:gcids) { '12345^PI^516^USVHA^PCE' } it 'is valid' do expect(user_info).to be_valid end end describe 'multiple valid GCID codes' do let(:gcids) do '1000123456V123456^NI^200M^USVHA^P|12345^PI^200PROV^USVHA^P|1234567890^NI^200DOD^USDOD^P' end it 'is valid' do expect(user_info).to be_valid end end describe 'mixed named and numeric GCID codes' do let(:gcids) do '1000123456V123456^NI^200M^USVHA^P|12345^PI^516^USVHA^PCE|2^PI^553^USVHA^PCE' end it 'is valid' do expect(user_info).to be_valid end end end context 'when gcids are invalid' do let(:expected_error_message) { 'contains non-approved gcids' } context 'when gcids contain an invalid code' do let(:gcids) do '1000123456V123456^NI^200BAD^USVHA^P|1000123456V123456^NI^200INVALID^USVHA^P' end it 'is not valid' do expect(user_info).not_to be_valid expect(user_info.errors[:gcids]).to include(expected_error_message) end end context 'when gcids contain mixed valid and invalid codes' do let(:gcids) do '1000123456V123456^NI^200M^USVHA^P|12345^PI^INVALID^USVHA^P|2^PI^553^USVHA^PCE' end it 'is not valid' do expect(user_info).not_to be_valid expect(user_info.errors[:gcids]).to include(expected_error_message) end end context 'when gcids is blank' do let(:gcids) { '' } it 'is valid (allows blank gcids)' do expect(user_info).to be_valid end end context 'when gcids is nil' do let(:gcids) { nil } it 'is valid (allows nil gcids)' do expect(user_info).to be_valid end end context 'when gcids is not a string' do let(:gcids) { %w[200M 200PROV] } it 'is not valid' do expect(user_info).not_to be_valid expect(user_info.errors[:gcids]).to include(expected_error_message) end end context 'when gcids contains segments with missing code' do let(:gcids) { '1000123456V123456^NI^^USVHA^P' } it 'is not valid' do expect(user_info).not_to be_valid expect(user_info.errors[:gcids]).to include(expected_error_message) end end context 'when gcids contains malformed segments' do let(:gcids) { '1000123456V123456' } it 'is not valid' do expect(user_info).not_to be_valid expect(user_info.errors[:gcids]).to include(expected_error_message) end end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/access_token_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::AccessToken, type: :model do let(:access_token) do create(:access_token, session_handle:, client_id:, user_uuid:, audience:, refresh_token_hash:, parent_refresh_token_hash:, anti_csrf_token:, last_regeneration_time:, expiration_time:, version:, created_time:, user_attributes:, device_secret_hash:) end let(:session_handle) { create(:oauth_session).handle } let(:user_uuid) { create(:user_account).id } let!(:client_config) do create(:client_config, authentication:, access_token_duration:, access_token_attributes:) end let(:access_token_duration) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_SHORT_MINUTES } let(:access_token_attributes) { SignIn::Constants::AccessToken::USER_ATTRIBUTES } let(:client_id) { client_config.client_id } let(:audience) { 'some-audience' } let(:authentication) { SignIn::Constants::Auth::API } let(:refresh_token_hash) { SecureRandom.hex } let(:parent_refresh_token_hash) { SecureRandom.hex } let(:anti_csrf_token) { SecureRandom.hex } let(:last_regeneration_time) { Time.zone.now } let(:version) { SignIn::Constants::AccessToken::CURRENT_VERSION } let(:validity_length) { client_config.access_token_duration } let(:expiration_time) { Time.zone.now + validity_length } let(:created_time) { Time.zone.now } let(:first_name) { Faker::Name.first_name } let(:last_name) { Faker::Name.last_name } let(:email) { Faker::Internet.email } let(:device_secret_hash) { SecureRandom.hex } let(:user_attributes) { { 'first_name' => first_name, 'last_name' => last_name, 'email' => email } } describe 'validations' do describe '#session_handle' do subject { access_token.session_handle } context 'when session_handle is nil' do let(:session_handle) { nil } let(:expected_error_message) { "Validation failed: Session handle can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#client_id' do subject { access_token.client_id } context 'when client_id is nil' do let(:client_id) { nil } let(:expected_error_message) { "Validation failed: Client can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#audience' do subject { access_token.audience } context 'when audience is nil' do let(:audience) { nil } let(:expected_error_message) { "Validation failed: Audience can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#user_uuid' do subject { access_token.user_uuid } context 'when user_uuid is nil' do let(:user_uuid) { nil } let(:expected_error_message) { "Validation failed: User uuid can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#refresh_token_hash' do subject { access_token.refresh_token_hash } context 'when refresh_token_hash is nil' do let(:refresh_token_hash) { nil } let(:expected_error_message) { "Validation failed: Refresh token hash can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#anti_csrf_token' do subject { access_token.anti_csrf_token } context 'when anti_csrf_token is nil' do let(:anti_csrf_token) { nil } let(:expected_error_message) { "Validation failed: Anti csrf token can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#last_regeneration_time' do subject { access_token.last_regeneration_time } context 'when last_regeneration_time is nil' do let(:last_regeneration_time) { nil } let(:expected_error_message) { "Validation failed: Last regeneration time can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#version' do subject { access_token.version } context 'when version is arbitrary' do let(:version) { 'some-arbitrary-version' } let(:expected_error_message) { 'Validation failed: Version is not included in the list' } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when version is nil' do let(:version) { nil } let(:expected_version) { SignIn::Constants::AccessToken::CURRENT_VERSION } it 'sets version to CURRENT_VERSION' do expect(subject).to be expected_version end end end describe '#expiration_time' do subject { access_token.expiration_time } before { Timecop.freeze } after { Timecop.return } context 'when expiration_time is nil' do let(:expiration_time) { nil } let(:expected_expiration_time) { Time.zone.now + validity_length } context 'and client_id refers to a short token expiration defined config' do let(:access_token_duration) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_SHORT_MINUTES } let(:validity_length) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_SHORT_MINUTES } it 'sets expired time to VALIDITY_LENGTH_SHORT_MINUTES from now' do expect(subject).to eq(expected_expiration_time) end end context 'and client_id refers to a long token expiration defined config' do let(:access_token_duration) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_LONG_MINUTES } let(:validity_length) { SignIn::Constants::AccessToken::VALIDITY_LENGTH_LONG_MINUTES } it 'sets expired time to VALIDITY_LENGTH_LONG_MINUTES from now' do expect(subject).to eq(expected_expiration_time) end end end end describe '#created_time' do subject { access_token.created_time } before { Timecop.freeze } after { Timecop.return } context 'when created_time is nil' do let(:created_time) { nil } let(:expected_created_time) { Time.zone.now } it 'sets expired time to now' do expect(subject).to eq(expected_created_time) end end end describe '#user_attributes' do subject { access_token.user_attributes } context 'when attributes are present in the ClientConfig access_token_attributes' do it 'includes those attributes in the access token' do expect(subject['first_name']).to eq(first_name) expect(subject['last_name']).to eq(last_name) expect(subject['email']).to eq(email) end end context 'when one or more attributes are not present in the ClientConfig access_token_attributes' do let(:access_token_attributes) { %w[email] } it 'does not include those attributes in the access token' do expect(subject['first_name']).to be_nil expect(subject['last_name']).to be_nil expect(subject['email']).to eq(email) end end context 'when no attributes are present in the ClientConfig access_token_attributes' do let(:access_token_attributes) { [] } it 'sets an empty hash object in the access token' do expect(subject).to eq({}) end end end end describe '#to_s' do subject { access_token.to_s } let(:expected_hash) do { uuid: access_token.uuid, user_uuid: access_token.user_uuid, session_handle: access_token.session_handle, client_id: access_token.client_id, audience: access_token.audience, version: access_token.version, last_regeneration_time: access_token.last_regeneration_time.to_i, created_time: access_token.created_time.to_i, expiration_time: access_token.expiration_time.to_i } end it 'returns a hash of expected values' do expect(subject).to eq(expected_hash) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/service_account_access_token_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::ServiceAccountAccessToken, type: :model do let(:service_account_access_token) do create(:service_account_access_token, service_account_id:, audience:, user_attributes:, user_identifier:, scopes:, expiration_time:, version:, created_time:) end let(:service_account_id) { service_account_config.service_account_id } let!(:service_account_config) { create(:service_account_config) } let(:audience) { 'some-audience' } let(:user_attributes) { { 'foo' => 'bar' } } let(:user_identifier) { 'some-user-identifier' } let(:scopes) { [scope] } let(:scope) { 'some-scope' } let(:version) { SignIn::Constants::ServiceAccountAccessToken::CURRENT_VERSION } let(:validity_length) { service_account_config.access_token_duration } let(:expiration_time) { Time.zone.now + validity_length } let(:created_time) { Time.zone.now } describe 'validations' do describe '#service_account_id' do subject { service_account_access_token.service_account_id } context 'when service_account_id is nil' do let(:service_account_id) { nil } let(:expected_error_message) { "Validation failed: Service account can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#audience' do subject { service_account_access_token.audience } context 'when audience is nil' do let(:audience) { nil } let(:expected_error_message) { "Validation failed: Audience can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#user_identifier' do subject { service_account_access_token.user_identifier } context 'when user_identifier is nil' do let(:user_identifier) { nil } let(:expected_error_message) { "Validation failed: User identifier can't be blank" } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#version' do subject { service_account_access_token.version } context 'when version is arbitrary' do let(:version) { 'some-arbitrary-version' } let(:expected_error_message) { 'Validation failed: Version is not included in the list' } let(:expected_error) { ActiveModel::ValidationError } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when version is nil' do let(:version) { nil } let(:expected_version) { SignIn::Constants::ServiceAccountAccessToken::CURRENT_VERSION } it 'sets version to CURRENT_VERSION' do expect(subject).to be expected_version end end end describe '#expiration_time' do subject { service_account_access_token.expiration_time } before { Timecop.freeze } after { Timecop.return } context 'when expiration_time is nil' do let(:expiration_time) { nil } let(:expected_expiration_time) { Time.zone.now + validity_length } it 'sets expired time to VALIDITY_LENGTH_SHORT_MINUTES from now' do expect(subject).to eq(expected_expiration_time) end end end describe '#created_time' do subject { service_account_access_token.created_time } before { Timecop.freeze } after { Timecop.return } context 'when created_time is nil' do let(:created_time) { nil } let(:expected_created_time) { Time.zone.now } it 'sets expired time to now' do expect(subject).to eq(expected_created_time) end end end end describe '#to_s' do subject { service_account_access_token.to_s } let(:expected_hash) do { uuid: service_account_access_token.uuid, service_account_id: service_account_access_token.service_account_id, user_attributes: service_account_access_token.user_attributes, user_identifier: service_account_access_token.user_identifier, scopes: service_account_access_token.scopes, audience: service_account_access_token.audience, version: service_account_access_token.version, created_time: service_account_access_token.created_time.to_i, expiration_time: service_account_access_token.expiration_time.to_i } end it 'returns a hash of expected values' do expect(subject).to eq(expected_hash) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/state_payload_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::StatePayload, type: :model do let(:state_payload) do create(:state_payload, code_challenge:, client_id:, type:, acr:, code:, client_state:, created_at:, scope:) end let(:code_challenge) { Base64.urlsafe_encode64(SecureRandom.hex) } let(:type) { SignIn::Constants::Auth::CSP_TYPES.first } let(:acr) { SignIn::Constants::Auth::ACR_VALUES.first } let(:code) { SecureRandom.hex } let(:client_config) { create(:client_config) } let(:client_id) { client_config.client_id } let(:client_state) { SecureRandom.hex } let(:created_at) { Time.zone.now.to_i } let(:scope) { SignIn::Constants::Auth::DEVICE_SSO } describe 'validations' do describe '#code' do subject { state_payload.code } context 'when code is nil' do let(:code) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Code can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#type' do subject { state_payload.type } context 'when type is nil' do let(:type) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Type is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when type is arbitrary' do let(:type) { 'some-type' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Type is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#client_id' do subject { state_payload.client_id } context 'when client_id is nil' do let(:client_id) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Client id must map to a configuration' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when client_id is an arbitrary value' do let(:client_id) { 'some-client-id' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Client id must map to a configuration' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#acr' do subject { state_payload.acr } context 'when acr is nil' do let(:acr) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Acr is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when acr is an arbitrary value' do let(:acr) { 'some-acr' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Acr is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#client_state' do subject { state_payload.client_state } context 'when client_state is shorter than minimum length' do let(:client_state) { SecureRandom.alphanumeric(SignIn::Constants::Auth::CLIENT_STATE_MINIMUM_LENGTH - 1) } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Client state is too short (minimum is 22 characters)' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end describe '#created_at' do subject { state_payload.created_at } before { Timecop.freeze } after { Timecop.return } context 'when created_at is nil' do let(:created_at) { nil } let(:expected_time) { Time.zone.now.to_i } it 'sets created_at to current time' do expect(subject).to eq(expected_time) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/refresh_token_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::RefreshToken, type: :model do let(:refresh_token) do create(:refresh_token, user_uuid:, uuid:, session_handle:, anti_csrf_token:, nonce:, version:) end let(:user_uuid) { create(:user).uuid } let(:uuid) { 'some-uuid' } let(:session_handle) { 'some-session-handle' } let(:anti_csrf_token) { 'some-anti-csrf-token' } let(:nonce) { 'some-nonce' } let(:version) { SignIn::Constants::RefreshToken::CURRENT_VERSION } describe '#initialize' do subject { refresh_token } context 'when user_uuid does not exist' do let(:user_uuid) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: User uuid can't be blank" } it 'raises a missing user_uuid validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when session_handle does not exist' do let(:session_handle) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Session handle can't be blank" } it 'raises a missing session_handle validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when anti_csrf_token does not exist' do let(:anti_csrf_token) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Anti csrf token can't be blank" } it 'raises a missing anti_csrf_token validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when nil nonce is passed in' do let(:nonce) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Nonce can't be blank" } it 'raises a missing nonce validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when nonce param is not defined' do let(:refresh_token) do SignIn::RefreshToken.new(user_uuid:, session_handle:, anti_csrf_token:) end let(:expected_random_number) { 'some-random-number' } before do allow(SecureRandom).to receive(:hex).and_return(expected_random_number) end it 'sets the nonce to a random value' do expect(subject.nonce).to eq(expected_random_number) end end context 'when nil uuid is passed in' do let(:uuid) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Uuid can't be blank" } it 'raises a missing uuid validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when uuid param is not defined' do let(:refresh_token) do SignIn::RefreshToken.new(user_uuid:, session_handle:, anti_csrf_token:) end let(:expected_random_number) { 'some-random-number' } before do allow(SecureRandom).to receive(:hex).and_return(expected_random_number) end it 'sets the uuid to a random value' do expect(subject.nonce).to eq(expected_random_number) end end context 'when nil version is passed in' do let(:version) { nil } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { "Validation failed: Version can't be blank, Version is not included in the list" } it 'raises a missing version validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when arbitrary version is passed in' do let(:version) { 'banana' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Version is not included in the list' } it 'raises a version not included in list validation error' do expect { subject }.to raise_exception(expected_error, expected_error_message) end end context 'when version param is not defined' do let(:refresh_token) do SignIn::RefreshToken.new(user_uuid:, session_handle:, anti_csrf_token:) end let(:expected_version) { SignIn::Constants::RefreshToken::CURRENT_VERSION } it 'sets the version to the current version' do expect(subject.version).to eq(expected_version) end end it 'returns a valid RefreshToken object' do expect(subject).to eq(refresh_token) expect(subject).to be_valid end end describe '#to_s' do subject { refresh_token.to_s } let(:expected_hash) do { uuid: refresh_token.uuid, user_uuid: refresh_token.user_uuid, session_handle: refresh_token.session_handle, version: refresh_token.version } end it 'returns a hash of expected values' do expect(subject).to eq(expected_hash) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/terms_code_container_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::TermsCodeContainer, type: :model do let(:terms_code_container) { create(:terms_code_container, user_account_uuid:, code:) } let(:code) { SecureRandom.hex } let(:user_account_uuid) { SecureRandom.uuid } describe 'validations' do describe '#code' do subject { terms_code_container.code } context 'when code is nil' do let(:code) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#user_account_uuid' do subject { terms_code_container.user_account_uuid } context 'when user_account_uuid is nil' do let(:user_account_uuid) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/credential_level_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::CredentialLevel, type: :model do let(:credential_level) do create(:credential_level, requested_acr:, current_ial:, max_ial:, credential_type:) end let(:requested_acr) { SignIn::Constants::Auth::ACR_VALUES.first } let(:current_ial) { SignIn::Constants::Auth::IAL_ONE } let(:max_ial) { SignIn::Constants::Auth::IAL_ONE } let(:credential_type) { SignIn::Constants::Auth::CSP_TYPES.first } describe 'validations' do describe '#requested_acr' do subject { credential_level.requested_acr } context 'when requested_acr is an arbitrary value' do let(:requested_acr) { 'some-requested-acr' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Requested acr is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#credential_type' do subject { credential_level.credential_type } context 'when credential_type is an arbitrary value' do let(:credential_type) { 'some-credential-type' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Credential type is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#current_ial' do subject { credential_level.current_ial } context 'when current_ial is an arbitrary value' do let(:current_ial) { 'some-current-ial' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Current ial is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#max_ial' do subject { credential_level.max_ial } context 'when max_ial is an arbitrary value' do let(:max_ial) { 'some-max-ial' } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) do 'Validation failed: Max ial is not included in the list, Max ial cannot be less than Current ial' end it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when max_ial is less than current_ial' do let(:max_ial) { SignIn::Constants::Auth::IAL_ONE } let(:current_ial) { SignIn::Constants::Auth::IAL_TWO } let(:expected_error) { ActiveModel::ValidationError } let(:expected_error_message) { 'Validation failed: Max ial cannot be less than Current ial' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end describe '#can_uplevel_credential?' do subject { credential_level.can_uplevel_credential? } context 'when requested acr is min' do let(:requested_acr) { SignIn::Constants::Auth::MIN } context 'and current_ial is less than max_ial' do let(:current_ial) { SignIn::Constants::Auth::IAL_ONE } let(:max_ial) { SignIn::Constants::Auth::IAL_TWO } it 'returns true' do expect(subject).to be(true) end end context 'and current_ial is equal to max_ial' do let(:current_ial) { SignIn::Constants::Auth::IAL_ONE } let(:max_ial) { SignIn::Constants::Auth::IAL_ONE } it 'returns false' do expect(subject).to be(false) end end end context 'when requested acr is some other value' do let(:requested_acr) { SignIn::Constants::Auth::ACR_VALUES.first } it 'returns false' do expect(subject).to be(false) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/sign_in/service_account_config_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::ServiceAccountConfig, type: :model do let(:service_account_id) { SecureRandom.hex } let(:access_token_duration) { SignIn::Constants::ServiceAccountAccessToken::VALIDITY_LENGTH_SHORT_MINUTES } let(:description) { 'some-description' } let(:access_token_audience) { 'some-access-token-audience' } let(:access_token_user_attributes) { [] } let(:service_account_config) do create(:service_account_config, service_account_id:, access_token_duration:, description:, access_token_audience:, access_token_user_attributes:) end describe 'associations' do it { is_expected.to have_many(:config_certificates).dependent(:destroy) } it { is_expected.to have_many(:certs).through(:config_certificates).class_name('SignIn::Certificate') } end describe 'validations' do let(:expected_error) { ActiveRecord::RecordInvalid } describe '#service_account_id' do subject { service_account_config.service_account_id } context 'when service_account_id is nil' do let(:service_account_id) { nil } let(:expected_error_message) { "Validation failed: Service account can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when service_account_id is not unique' do let!(:old_service_account_config) { create(:service_account_config) } let(:service_account_id) { old_service_account_config.service_account_id } let(:expected_error_message) { 'Validation failed: Service account has already been taken' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#description' do subject { service_account_config.description } context 'when description is nil' do let(:description) { nil } let(:expected_error_message) { "Validation failed: Description can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token_audience' do subject { service_account_config.access_token_audience } context 'when access_token_audience is empty' do let(:access_token_audience) { nil } let(:expected_error_message) { "Validation failed: Access token audience can't be blank" } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token_duration' do subject { service_account_config.access_token_duration } let(:validity_length) { SignIn::Constants::ServiceAccountAccessToken::VALIDITY_LENGTH_SHORT_MINUTES } context 'when access_token_duration is empty' do let(:access_token_duration) { nil } let(:expected_error_message) do "Validation failed: Access token duration can't be blank, Access token duration is not included in the list" end it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when access_token_duration is an arbitrary interval' do let(:access_token_duration) { 300.days } let(:expected_error_message) { 'Validation failed: Access token duration is not included in the list' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#access_token_user_attributes' do subject { service_account_config.access_token_user_attributes } let(:expected_error_message) do 'Validation failed: Access token user attributes is not included in the list' end context 'when access_token_user_attributes is empty' do it 'does not raise validation error' do expect { subject }.not_to raise_error end end context 'when access_token_user_attributes contains an unallowed item' do let(:access_token_user_attributes) { ['foo'] } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end context 'when access_token_user_attributes contains an allowed item' do let(:access_token_user_attributes) { items } context 'and it contains only allowed items' do let(:items) { ['icn'] } it 'does not raise validation error' do expect { subject }.not_to raise_error end end context 'and it also contains an unallowed item' do let(:items) { %w[icn foo] } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/chatbot/code_container_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Chatbot::CodeContainer, type: :model do let(:chatbot_code_container) do create(:chatbot_code_container, code:, icn:) end let(:code) { 'some-code' } let(:icn) { 'some-icn' } describe 'validations' do describe '#code' do subject { chatbot_code_container.code } context 'when code is nil' do let(:code) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end describe '#icn' do subject { chatbot_code_container.icn } context 'when icn is nil' do let(:icn) { nil } let(:expected_error) { Common::Exceptions::ValidationErrors } let(:expected_error_message) { 'Validation error' } it 'raises validation error' do expect { subject }.to raise_error(expected_error, expected_error_message) end end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs/submission_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'support/models/shared_examples/submission' RSpec.describe BGS::Submission, type: :model do # Use shared examples but skip the problematic latest_attempt test that doesn't work with foreign keys it { is_expected.to validate_presence_of :form_id } describe 'encrypted attributes' do it 'responds to encrypted fields' do subject = described_class.new expect(subject).to respond_to(:reference_data) end end # Override the shared example that doesn't work with BGS foreign key constraints describe '#latest_attempt (shared example override)' do it 'returns the last attempt' do submission = create(:bgs_submission) expect(submission.latest_attempt).to be_nil attempts = [] 5.times { attempts << create(:bgs_submission_attempt, submission:) } expect(submission.submission_attempts.length).to eq 5 expect(submission.latest_attempt).to eq attempts.last end end describe 'database configuration' do it 'uses the correct table name' do expect(described_class.table_name).to eq('bgs_submissions') end end describe 'includes' do it 'includes SubmissionEncryption' do expect(described_class.included_modules).to include(SubmissionEncryption) end end describe 'associations' do it { is_expected.to have_many(:submission_attempts).class_name('BGS::SubmissionAttempt') } it { is_expected.to have_many(:submission_attempts).dependent(:destroy) } it { is_expected.to have_many(:submission_attempts).with_foreign_key(:bgs_submission_id) } it { is_expected.to have_many(:submission_attempts).inverse_of(:submission) } it { is_expected.to belong_to(:saved_claim).optional } end describe 'inheritance' do it 'inherits from Submission' do expect(described_class.superclass).to eq(Submission) end end describe '#latest_attempt' do let(:submission) { create(:bgs_submission) } context 'when no attempts exist' do it 'returns nil' do expect(submission.latest_attempt).to be_nil end end context 'when multiple attempts exist' do let!(:first_attempt) { create(:bgs_submission_attempt, submission:, created_at: 2.hours.ago) } let!(:second_attempt) { create(:bgs_submission_attempt, submission:, created_at: 1.hour.ago) } let!(:latest_attempt) { create(:bgs_submission_attempt, submission:, created_at: 30.minutes.ago) } it 'returns the most recently created attempt' do expect(submission.latest_attempt).to eq(latest_attempt) end it 'orders by created_at descending and takes the first' do attempts = submission.submission_attempts.order(created_at: :desc) expect(attempts.to_a).to eq([latest_attempt, second_attempt, first_attempt]) expect(submission.latest_attempt).to eq(attempts.first) end end end describe '#latest_pending_attempt' do let(:submission) { create(:bgs_submission) } context 'when no pending attempts exist' do before do create(:bgs_submission_attempt, submission:, status: 'submitted') create(:bgs_submission_attempt, submission:, status: 'failure') end it 'returns nil' do expect(submission.latest_pending_attempt).to be_nil end end context 'when multiple pending attempts exist' do let!(:first_pending) do create(:bgs_submission_attempt, submission:, status: 'pending', created_at: 2.hours.ago) end let!(:submitted_attempt) do create(:bgs_submission_attempt, submission:, status: 'submitted', created_at: 1.hour.ago) end let!(:latest_pending) do create(:bgs_submission_attempt, submission:, status: 'pending', created_at: 30.minutes.ago) end it 'returns the most recently created pending attempt' do expect(submission.latest_pending_attempt).to eq(latest_pending) end it 'ignores non-pending attempts' do pending_attempts = submission.submission_attempts.where(status: 'pending') expect(pending_attempts.count).to eq(2) expect(submission.latest_pending_attempt).to eq(latest_pending) end end context 'when only one pending attempt exists' do let!(:pending_attempt) { create(:bgs_submission_attempt, submission:, status: 'pending') } it 'returns that pending attempt' do expect(submission.latest_pending_attempt).to eq(pending_attempt) end end end describe '#non_failure_attempt' do let(:submission) { create(:bgs_submission) } context 'when no non-failure attempts exist' do before do create(:bgs_submission_attempt, submission:, status: 'failure') create(:bgs_submission_attempt, submission:, status: 'failure') end it 'returns nil' do expect(submission.non_failure_attempt).to be_nil end end context 'when multiple non-failure attempts exist' do let!(:failure_attempt) do create(:bgs_submission_attempt, submission:, status: 'failure', created_at: 3.hours.ago) end let!(:pending_attempt) do create(:bgs_submission_attempt, submission:, status: 'pending', created_at: 2.hours.ago) end let!(:submitted_attempt) do create(:bgs_submission_attempt, submission:, status: 'submitted', created_at: 1.hour.ago) end it 'returns the first non-failure attempt (pending or submitted)' do expect(submission.non_failure_attempt).to eq(pending_attempt) end it 'excludes failure attempts' do non_failure_attempts = submission.submission_attempts.where(status: %w[pending submitted]) expect(non_failure_attempts.count).to eq(2) expect(submission.non_failure_attempt).to eq(non_failure_attempts.first) end end context 'when only pending attempts exist' do let!(:pending_attempt) { create(:bgs_submission_attempt, submission:, status: 'pending') } it 'returns the pending attempt' do expect(submission.non_failure_attempt).to eq(pending_attempt) end end context 'when only submitted attempts exist' do let!(:submitted_attempt) { create(:bgs_submission_attempt, submission:, status: 'submitted') } it 'returns the submitted attempt' do expect(submission.non_failure_attempt).to eq(submitted_attempt) end end end describe 'encrypted attributes functionality' do let(:submission) { build(:bgs_submission) } it 'responds to reference_data' do expect(submission).to respond_to(:reference_data) end it 'can set and retrieve reference_data' do reference_data = { 'icn' => '1234567890V123456', 'ssn' => '123456789' } submission.reference_data = reference_data expect(submission.reference_data).to eq(reference_data) end end describe 'validations' do it { is_expected.to validate_presence_of(:form_id) } end describe 'factory' do it 'can create a valid submission' do submission = build(:bgs_submission) expect(submission).to be_valid end it 'creates submission with correct attributes' do submission = create(:bgs_submission, form_id: '21-686C') expect(submission.form_id).to eq('21-686C') expect(submission.latest_status).to be_present expect(submission.saved_claim).to be_present end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs/submission_attempt_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'support/models/shared_examples/submission_attempt' RSpec.describe BGS::SubmissionAttempt, type: :model do let(:submission_attempt) { build(:bgs_submission_attempt) } it_behaves_like 'a SubmissionAttempt model' describe 'database configuration' do it 'uses the correct table name' do expect(described_class.table_name).to eq('bgs_submission_attempts') end end describe 'inheritance' do it 'inherits from SubmissionAttempt' do expect(described_class.superclass).to eq(SubmissionAttempt) end end describe 'includes' do it 'includes SubmissionAttemptEncryption' do expect(described_class.included_modules).to include(SubmissionAttemptEncryption) end end describe 'associations' do it { is_expected.to belong_to(:submission).class_name('BGS::Submission') } it { is_expected.to belong_to(:submission).with_foreign_key(:bgs_submission_id) } it { is_expected.to belong_to(:submission).inverse_of(:submission_attempts) } it { is_expected.to have_one(:saved_claim).through(:submission) } end describe 'enums' do # BGS::SubmissionAttempt uses a database enum, not an integer-backed Rails enum it 'has status enum with correct values' do expect(described_class.statuses).to eq({ 'pending' => 'pending', 'submitted' => 'submitted', 'failure' => 'failure' }) end it 'responds to status enum methods' do attempt = build(:bgs_submission_attempt) expect(attempt).to respond_to(:pending?) expect(attempt).to respond_to(:submitted?) expect(attempt).to respond_to(:failure?) end describe 'status values' do it 'has correct enum values' do expect(described_class.statuses).to eq({ 'pending' => 'pending', 'submitted' => 'submitted', 'failure' => 'failure' }) end end end describe 'constants' do it 'defines STATS_KEY' do expect(described_class::STATS_KEY).to eq('api.bgs.submission_attempt') end end describe '#fail!' do let(:submission_attempt) { create(:bgs_submission_attempt, status: 'pending') } let(:error) { StandardError.new('Test error message') } let(:monitor) { instance_double(Logging::Monitor) } before do allow(submission_attempt).to receive(:monitor).and_return(monitor) allow(monitor).to receive(:track_request) end it 'updates error_message with the error message' do submission_attempt.fail!(error:) expect(submission_attempt.error_message).to eq('Test error message') end it 'sets status to failure' do submission_attempt.fail!(error:) expect(submission_attempt.status).to eq('failure') end it 'handles nil error gracefully' do submission_attempt.fail!(error: nil) expect(submission_attempt.error_message).to be_nil expect(submission_attempt.status).to eq('failure') end it 'tracks the error with monitor' do expect(monitor).to receive(:track_request).with( :error, 'BGS Submission Attempt failed', 'api.bgs.submission_attempt', hash_including( submission_id: submission_attempt.submission.id, form_type: submission_attempt.submission.form_id, from_state: 'pending', to_state: 'failure', message: 'BGS Submission Attempt failed' ) ) submission_attempt.fail!(error:) end end describe '#pending!' do let(:submission_attempt) { create(:bgs_submission_attempt, status: 'submitted') } let(:monitor) { instance_double(Logging::Monitor) } before do allow(submission_attempt).to receive(:monitor).and_return(monitor) allow(monitor).to receive(:track_request) end it 'sets status to pending' do submission_attempt.pending! expect(submission_attempt.status).to eq('pending') end it 'tracks the status change with monitor' do expect(monitor).to receive(:track_request).with( :info, 'BGS Submission Attempt is pending', 'api.bgs.submission_attempt', hash_including( submission_id: submission_attempt.submission.id, form_type: submission_attempt.submission.form_id, from_state: 'submitted', to_state: 'pending', message: 'BGS Submission Attempt is pending' ) ) submission_attempt.pending! end end describe '#success!' do let(:submission_attempt) { create(:bgs_submission_attempt, status: 'pending') } let(:monitor) { instance_double(Logging::Monitor) } before do allow(submission_attempt).to receive(:monitor).and_return(monitor) allow(monitor).to receive(:track_request) end it 'sets status to submitted' do submission_attempt.success! expect(submission_attempt.status).to eq('submitted') end it 'tracks the status change with monitor' do expect(monitor).to receive(:track_request).with( :info, 'BGS Submission Attempt is submitted', 'api.bgs.submission_attempt', hash_including( submission_id: submission_attempt.submission.id, form_type: submission_attempt.submission.form_id, from_state: 'pending', to_state: 'submitted', message: 'BGS Submission Attempt is submitted' ) ) submission_attempt.success! end end describe '#monitor' do it 'returns a Logging::Monitor instance' do expect(submission_attempt.monitor).to be_a(Logging::Monitor) end it 'memoizes the monitor instance' do first_call = submission_attempt.monitor second_call = submission_attempt.monitor expect(first_call).to be(second_call) end it 'initializes monitor with correct name' do expect(Logging::Monitor).to receive(:new).with('bgs_submission_attempt').and_call_original submission_attempt.monitor end end describe '#status_change_hash' do let(:submission) { create(:bgs_submission, form_id: '21-686C') } let(:submission_attempt) { create(:bgs_submission_attempt, submission:, status: 'pending') } context 'when status changes' do before do submission_attempt.update(status: 'submitted') end it 'returns hash with correct structure' do hash = submission_attempt.status_change_hash expect(hash).to include( submission_id: submission.id, claim_id: submission.saved_claim_id, form_type: '21-686C', from_state: 'pending', to_state: 'submitted' ) end end context 'when no status change has occurred' do it 'returns hash with nil from_state' do hash = submission_attempt.status_change_hash expect(hash).to include( submission_id: submission.id, claim_id: submission.saved_claim_id, form_type: '21-686C', from_state: nil, to_state: 'pending' ) end end end describe 'encrypted attributes' do let(:submission_attempt) { build(:bgs_submission_attempt) } it 'responds to encrypted fields' do expect(submission_attempt).to respond_to(:metadata) expect(submission_attempt).to respond_to(:error_message) expect(submission_attempt).to respond_to(:response) end it 'can set and retrieve metadata' do metadata = { 'form_id' => '21-686C', 'submission_type' => 'bgs' } submission_attempt.metadata = metadata expect(submission_attempt.metadata).to eq(metadata) end it 'can set and retrieve error_message' do error_message = { 'error_class' => 'BGS::ServiceError', 'error_message' => 'Service unavailable' } submission_attempt.error_message = error_message expect(submission_attempt.error_message).to eq(error_message) end it 'can set and retrieve response' do response = { 'claim_id' => '12345678', 'success' => true } submission_attempt.response = response expect(submission_attempt.response).to eq(response) end end describe 'status transitions' do let(:submission_attempt) { create(:bgs_submission_attempt) } context 'from pending' do before { submission_attempt.update(status: 'pending') } it 'can transition to submitted' do expect { submission_attempt.success! }.to change(submission_attempt, :status).from('pending').to('submitted') end it 'can transition to failure' do expect { submission_attempt.fail!(error: StandardError.new('Error')) } .to change(submission_attempt, :status).from('pending').to('failure') end end context 'from submitted' do before { submission_attempt.update(status: 'submitted') } it 'can transition back to pending' do expect { submission_attempt.pending! }.to change(submission_attempt, :status).from('submitted').to('pending') end it 'can transition to failure' do expect { submission_attempt.fail!(error: StandardError.new('Error')) } .to change(submission_attempt, :status).from('submitted').to('failure') end end context 'from failure' do before { submission_attempt.update(status: 'failure') } it 'can transition back to pending' do expect { submission_attempt.pending! }.to change(submission_attempt, :status).from('failure').to('pending') end it 'can transition to submitted' do expect { submission_attempt.success! }.to change(submission_attempt, :status).from('failure').to('submitted') end end end describe 'factory' do it 'can create a valid submission attempt' do submission_attempt = build(:bgs_submission_attempt) expect(submission_attempt).to be_valid end it 'creates submission attempt with correct attributes' do submission_attempt = create(:bgs_submission_attempt, :submitted) expect(submission_attempt.status).to eq('submitted') expect(submission_attempt.submission).to be_present expect(submission_attempt.metadata).to be_present end it 'creates submission attempt with different traits' do pending_attempt = create(:bgs_submission_attempt, :pending) failure_attempt = create(:bgs_submission_attempt, :failure) expect(pending_attempt.status).to eq('pending') expect(failure_attempt.status).to eq('failure') end end describe 'callbacks and validations' do it 'validates presence of submission' do submission_attempt = build(:bgs_submission_attempt, submission: nil) expect(submission_attempt).not_to be_valid expect(submission_attempt.errors[:submission]).to include("can't be blank") end it 'updates submission status when attempt status changes' do submission = create(:bgs_submission) submission_attempt = create(:bgs_submission_attempt, submission:, status: 'pending') expect { submission_attempt.update(status: 'submitted') } .to change { submission.reload.latest_status }.from('pending').to('submitted') end end describe '.by_claim_group' do let(:parent_claim) { create(:dependents_claim) } let(:child_claim1) { create(:add_remove_dependents_claim) } let(:child_claim2) { create(:student_claim) } let(:other_parent_claim) { create(:dependents_claim) } let(:other_child_claim) { create(:add_remove_dependents_claim) } let!(:claim_group1) do create(:saved_claim_group, parent_claim:, saved_claim: child_claim1, status: 'pending') end let!(:claim_group2) do create(:saved_claim_group, parent_claim:, saved_claim: child_claim2, status: 'pending') end let!(:other_claim_group) do create(:saved_claim_group, parent_claim: other_parent_claim, saved_claim: other_child_claim, status: 'pending') end let!(:submission1) { create(:bgs_submission, saved_claim: child_claim1) } let!(:submission2) { create(:bgs_submission, saved_claim: child_claim2) } let!(:other_submission) { create(:bgs_submission, saved_claim: other_child_claim) } let!(:attempt1) { create(:bgs_submission_attempt, submission: submission1, status: 'pending') } let!(:attempt2) { create(:bgs_submission_attempt, submission: submission2, status: 'pending') } let!(:submitted_attempt) { create(:bgs_submission_attempt, submission: submission1, status: 'submitted') } let!(:other_attempt) { create(:bgs_submission_attempt, submission: other_submission, status: 'pending') } it 'returns submission attempts for a specific parent claim group' do results = described_class.by_claim_group(parent_claim.id) expect(results).to include(attempt1, attempt2, submitted_attempt) expect(results).not_to include(other_attempt) end it 'can be chained with .pending to filter by status' do results = described_class.by_claim_group(parent_claim.id).pending expect(results).to include(attempt1, attempt2) expect(results).not_to include(submitted_attempt) expect(results.pluck(:status).uniq).to eq(['pending']) end it 'returns empty relation when no matching claim groups exist' do non_existent_parent_id = parent_claim.id + 9999 results = described_class.by_claim_group(non_existent_parent_id) expect(results).to be_empty end it 'is chainable with other scopes' do results = described_class.by_claim_group(parent_claim.id).where(id: attempt1.id) expect(results).to contain_exactly(attempt1) end it 'joins through submission, saved_claim, and claim groups correctly' do results = described_class.by_claim_group(parent_claim.id) expect(results.to_sql).to include('saved_claim_groups') expect(results.to_sql).to include('saved_claims') expect(results.to_sql).to include('bgs_submissions') end end describe '#claim_type_end_product' do context 'when metadata contains claim_type_end_product' do let(:submission_attempt) do create(:bgs_submission_attempt, metadata: { claim_type_end_product: '130' }.to_json) end it 'returns the claim_type_end_product value' do expect(submission_attempt.claim_type_end_product).to eq('130') end end context 'when metadata does not contain claim_type_end_product' do let(:submission_attempt) do create(:bgs_submission_attempt, metadata: { form_id: '21-686C' }.to_json) end it 'returns nil' do expect(submission_attempt.claim_type_end_product).to be_nil end end context 'when metadata is nil' do let(:submission_attempt) do create(:bgs_submission_attempt, metadata: nil) end it 'returns nil without raising an error' do expect(submission_attempt.claim_type_end_product).to be_nil end end context 'when metadata is an empty string' do let(:submission_attempt) do create(:bgs_submission_attempt, metadata: '') end it 'returns nil without raising an error' do expect(submission_attempt.claim_type_end_product).to be_nil end end context 'when metadata contains complex nested structure' do let(:submission_attempt) do create(:bgs_submission_attempt) end before do metadata = submission_attempt.metadata || {} metadata['claim_type_end_product'] = '134' submission_attempt.metadata = metadata.to_json submission_attempt.save! end it 'correctly extracts claim_type_end_product' do expect(submission_attempt.claim_type_end_product).to eq('134') end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/async_transaction/base_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe AsyncTransaction::Base, type: :model do describe 'Validation' do let(:transaction1) { create(:address_transaction) } let(:transaction2) { build(:address_transaction) } let(:transaction3) { build(:address_transaction, source: nil) } let(:transaction4) { build(:address_transaction) } it 'ensures uniqueness across source and transaction_id', :aggregate_failures do transaction2.transaction_id = transaction1.transaction_id expect(transaction2.valid?).to be false expect(transaction2.errors[:transaction_id]) .to eq(['Transaction ID must be unique within a source.']) end it 'ensures presence of required fields' do expect(transaction3.valid?).to be false end it 'accepts a FactoryBot-made transaction' do expect(transaction4.valid?).to be true end end describe 'Serialization' do let(:transaction) { build(:address_transaction) } it 'JSON encodes metadata' do transaction.update(metadata: { unserialized: 'data' }) expect(transaction.metadata.is_a?(String)).to be true end end describe 'Subclasses' do let(:transaction1) { create(:address_transaction, transaction_id: 1) } let(:transaction2) { create(:email_transaction, transaction_id: 2) } let(:transaction3) { create(:telephone_transaction, transaction_id: 3) } it 'are queryable from the parent', :aggregate_failures do record1 = AsyncTransaction::VAProfile::Base .where(transaction_id: transaction1.transaction_id, source: transaction1.source).first expect(record1.id).to eq(transaction1.id) expect(record1).to be_instance_of(AsyncTransaction::VAProfile::AddressTransaction) record2 = AsyncTransaction::VAProfile::Base .where(transaction_id: transaction2.transaction_id, source: transaction2.source).first expect(record2.id).to eq(transaction2.id) expect(record2).to be_instance_of(AsyncTransaction::VAProfile::EmailTransaction) record3 = AsyncTransaction::VAProfile::Base .where(transaction_id: transaction3.transaction_id, source: transaction3.source).first expect(record3.id).to eq(transaction3.id) expect(record3).to be_instance_of(AsyncTransaction::VAProfile::TelephoneTransaction) end end describe '.stale scope' do it 'finds transactions that are eligible to be destroyed', :aggregate_failures do stale_age = AsyncTransaction::Base::DELETE_COMPLETED_AFTER + 1.day active_age = AsyncTransaction::Base::DELETE_COMPLETED_AFTER - 1.day stale_transaction = create( :address_transaction, created_at: (Time.current - stale_age).iso8601, status: AsyncTransaction::Base::COMPLETED ) create( :telephone_transaction, created_at: (Time.current - active_age).iso8601, status: AsyncTransaction::Base::COMPLETED ) transactions = AsyncTransaction::Base.stale expect(transactions.count).to eq 1 expect(transactions.first).to eq stale_transaction end end end
0
code_files/vets-api-private/spec/models/async_transaction
code_files/vets-api-private/spec/models/async_transaction/va_profile/base_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe AsyncTransaction::VAProfile::Base, type: :model do describe '.refresh_transaction_status()' do let(:user) { build(:user, :loa3) } let(:transaction1) do create(:address_transaction, transaction_id: '0ea91332-4713-4008-bd57-40541ee8d4d4', user_uuid: user.uuid, transaction_status: 'RECEIVED') end let(:transaction2) do create(:email_transaction, transaction_id: '5b4550b3-2bcb-4fef-8906-35d0b4b310a8', user_uuid: user.uuid, transaction_status: 'RECEIVED') end let(:service) { VAProfile::ContactInformation::V2::Service.new(user) } before do # vet360_id appears in the API request URI so we need it to match the cassette allow_any_instance_of(MPIData).to receive(:response_from_redis_or_service).and_return( create(:find_profile_response, profile: build(:mpi_profile, vet360_id: '1')) ) end it 'updates the transaction_status' do VCR.use_cassette('va_profile/v2/contact_information/address_transaction_status') do updated_transaction = AsyncTransaction::VAProfile::Base.refresh_transaction_status( user, service, transaction1.transaction_id ) expect(updated_transaction.transaction_status).to eq('COMPLETED_SUCCESS') end end it 'updates the status' do VCR.use_cassette('va_profile/v2/contact_information/address_transaction_status') do updated_transaction = AsyncTransaction::VAProfile::Base.refresh_transaction_status( user, service, transaction1.transaction_id ) expect(updated_transaction.status).to eq(AsyncTransaction::VAProfile::Base::COMPLETED) end end it 'persists the messages from va_profile' do VCR.use_cassette('va_profile/v2/contact_information/email_transaction_status') do updated_transaction = AsyncTransaction::VAProfile::Base.refresh_transaction_status( user, service, transaction2.transaction_id ) expect(updated_transaction.persisted?).to be(true) parsed_metadata = JSON.parse(updated_transaction.metadata) expect(parsed_metadata.is_a?(Array)).to be(true) expect(updated_transaction.metadata.present?).to be(true) end end it 'raises an exception if transaction not found in db' do expect do AsyncTransaction::VAProfile::Base.refresh_transaction_status(user, service, 9_999_999) end.to raise_exception(ActiveRecord::RecordNotFound) end it 'does not make an API request if the tx is finished' do transaction1.status = AsyncTransaction::VAProfile::Base::COMPLETED VCR.use_cassette('va_profile/v2/contact_information/address_transaction_status') do AsyncTransaction::VAProfile::Base.refresh_transaction_status( user, service, transaction1.transaction_id ) expect(AsyncTransaction::VAProfile::Base).to receive(:fetch_transaction).at_most(0) end end end describe '.start' do let(:user) { build(:user, :loa3, :legacy_icn) } let(:address) { build(:va_profile_address, :mobile) } it 'returns an instance with the user uuid', :aggregate_failures do VCR.use_cassette('va_profile/v2/contact_information/post_address_success', VCR::MATCH_EVERYTHING) do service = VAProfile::ContactInformation::V2::Service.new(user) response = service.post_address(address) transaction = AsyncTransaction::VAProfile::Base.start(user, response) expect(transaction.user_uuid).to eq(user.uuid) expect(transaction.class).to eq(AsyncTransaction::VAProfile::Base) end end end describe '.fetch_transaction' do it 'raises an error if passed unrecognized transaction' do # Instead of simply calling Struct.new('Surprise'), we need to check that it hasn't been defined already # in order to prevent the following warning: # warning: redefining constant Struct::Surprise surprise_struct = Struct.const_defined?('Surprise') ? Struct::Surprise : Struct.new('Surprise') expect do AsyncTransaction::VAProfile::Base.fetch_transaction(surprise_struct, nil) end.to raise_exception(RuntimeError) end end describe '.refresh_transaction_statuses()' do let(:user) { build(:user, :loa3) } let(:transaction1) do create(:address_transaction, transaction_id: '0faf342f-5966-4d3f-8b10-5e9f911d07d2', user_uuid: user.uuid, status: AsyncTransaction::VAProfile::Base::COMPLETED) end let(:service) { VAProfile::ContactInformation::V2::Service.new(user) } before do # vet360_id appears in the API request URI so we need it to match the cassette allow_any_instance_of(MPIData).to receive(:response_from_redis_or_service).and_return( create(:find_profile_response, profile: build(:mpi_profile, vet360_id: '1')) ) end it 'does not return completed transactions (whose status has not changed)' do transactions = AsyncTransaction::VAProfile::Base.refresh_transaction_statuses(user, service) expect(transactions).to eq([]) end it 'returns only the most recent transaction address/telephone/email transaction' do create(:email_transaction, transaction_id: 'foo', user_uuid: user.uuid, transaction_status: 'RECEIVED', status: AsyncTransaction::VAProfile::Base::REQUESTED, created_at: Time.zone.now - 1) transaction = create(:email_transaction, transaction_id: '5b4550b3-2bcb-4fef-8906-35d0b4b310a8', user_uuid: user.uuid, transaction_status: 'RECEIVED', status: AsyncTransaction::VAProfile::Base::REQUESTED) VCR.use_cassette('va_profile/v2/contact_information/email_transaction_status', VCR::MATCH_EVERYTHING) do transactions = AsyncTransaction::VAProfile::Base.refresh_transaction_statuses(user, service) expect(transactions.size).to eq(1) expect(transactions.first.transaction_id).to eq(transaction.transaction_id) end end end end
0
code_files/vets-api-private/spec/models/veteran_enrollment_system
code_files/vets-api-private/spec/models/veteran_enrollment_system/form1095_b/form1095_b_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe VeteranEnrollmentSystem::Form1095B::Form1095B, type: :model do let(:form_data) do { 'data' => { 'issuer' => { 'issuerName' => 'US Department of Veterans Affairs', 'ein' => '54-2002017', 'contactPhoneNumber' => '877-222-8387', 'address' => { 'street1' => 'PO Box 149975', 'city' => 'Austin', 'stateOrProvince' => 'TX', 'zipOrPostalCode' => '78714-8975', 'country' => 'USA' } }, 'responsibleIndividual' => { 'name' => { 'firstName' => 'HECTOR', 'lastName' => 'ALLEN' }, 'address' => { 'street1' => 'PO BOX 494', 'city' => 'MOCA', 'stateOrProvince' => 'PR', 'zipOrPostalCode' => '00676-0494', 'country' => 'USA' }, 'ssn' => '796126859', 'dateOfBirth' => '19320205' }, 'coveredIndividual' => { 'name' => { 'firstName' => 'HECTOR', 'lastName' => 'ALLEN' }, 'ssn' => '796126859', 'dateOfBirth' => '19320205', 'coveredAll12Months' => false, 'monthsCovered' => ['MARCH'] }, 'taxYear' => '2024' }, 'messages' => [] } end let(:form1095b) { build(:enrollment_system_form1095_b) } describe '.parse' do it 'returns an instance of model with expected attributes' do rv = described_class.parse(form_data) expect(rv).to be_instance_of(described_class) expect(rv.attributes).to eq({ 'first_name' => 'HECTOR', 'middle_name' => nil, 'last_name' => 'ALLEN', 'last_4_ssn' => '6859', 'birth_date' => '1932-02-05'.to_date, 'address' => 'PO BOX 494', 'city' => 'MOCA', 'state' => 'PR', 'province' => 'PR', 'country' => 'USA', 'zip_code' => '00676-0494', 'foreign_zip' => '00676-0494', 'is_corrected' => false, 'coverage_months' => [ false, false, false, 'MARCH', false, false, false, false, false, false, false, false, false ], 'tax_year' => '2024' }) end it 'sets coveredAll12Months correctly' do form_data['data']['coveredIndividual']['coveredAll12Months'] = false instance = described_class.parse(form_data) expect(instance.coverage_months[0]).to be(false) form_data['data']['coveredIndividual']['coveredAll12Months'] = true instance = described_class.parse(form_data) expect(instance.coverage_months[0]).to be(true) end it 'sets covered months as expected' do form_data['data']['coveredIndividual']['monthsCovered'] = %w[MARCH SEPTEMBER] instance = described_class.parse(form_data) expect(instance.coverage_months[1..12]).to eq( [false, false, 'MARCH', false, false, false, false, false, 'SEPTEMBER', false, false, false] ) end it 'handles empty ssn' do form_data['data']['coveredIndividual']['ssn'] = '' instance = described_class.parse(form_data) expect(instance.last_4_ssn).to be_nil end it 'handles nil ssn' do form_data['data']['coveredIndividual']['ssn'] = nil instance = described_class.parse(form_data) expect(instance.last_4_ssn).to be_nil end end describe '.available_years' do before { Timecop.freeze(Time.zone.parse('2025-03-05T08:00:00Z')) } after { Timecop.return } context 'with start and end dates' do it 'returns all currently available years during which the user had coverage' do periods = [{ 'startDate' => '2015-03-05', 'endDate' => '2025-03-05' }] result = described_class.available_years(periods) expect(result).to eq([2024]) end end context 'when end date is nil' do it 'infers that the user is still covered and returns all currently available years' do periods = [{ 'startDate' => '2015-03-05', 'endDate' => nil }] result = described_class.available_years(periods) expect(result).to eq([2024]) end end context 'with multiple periods' do it 'returns all currently available years during which the user had coverage' do periods = [{ 'startDate' => '2015-03-05', 'endDate' => '2017-03-05' }, { 'startDate' => '2020-03-05', 'endDate' => '2021-03-05' }, { 'startDate' => '2022-03-05', 'endDate' => '2022-04-05' }, { 'startDate' => '2024-03-05', 'endDate' => nil }] result = described_class.available_years(periods) expect(result).to eq([2024]) end end context 'when user was not covered during available years' do it 'returns an empty array' do periods = [{ 'startDate' => '2015-03-05', 'endDate' => '2020-03-05' }] result = described_class.available_years(periods) expect(result).to eq([]) end end end describe '.available_years_range' do before { Timecop.freeze(Time.zone.parse('2025-03-05T08:00:00Z')) } after { Timecop.return } it 'returns an array containing first and last years of accessible 1095-B data' do result = described_class.available_years_range expect(result).to eq([2024, 2024]) end end describe '.pdf_template_path' do it 'returns the path to the pdf template' do expect(described_class.pdf_template_path(2023)).to eq( 'lib/veteran_enrollment_system/form1095_b/templates/pdfs/1095b-2023.pdf' ) end end describe '.txt_template_path' do it 'returns the path to the txt template' do expect(described_class.txt_template_path(2023)).to eq( 'lib/veteran_enrollment_system/form1095_b/templates/txts/1095b-2023.txt' ) end end describe '#pdf_file' do context 'when template is present' do it 'generates pdf string for valid 1095_b' do expect(form1095b.pdf_file.class).to eq(String) end end context 'when template is not present' do let(:inv_year_form) { build(:enrollment_system_form1095_b, tax_year: 2008) } it 'raises error' do expect { inv_year_form.pdf_file }.to raise_error(Common::Exceptions::UnprocessableEntity) end end end describe '#txt_file' do context 'when template is present' do it 'generates text string for valid 1095_b' do expect(form1095b.txt_file.class).to eq(String) end end context 'when template is not present' do let(:inv_year_form) { build(:enrollment_system_form1095_b, tax_year: 2008) } it 'raises error' do expect { inv_year_form.txt_file }.to raise_error(Common::Exceptions::UnprocessableEntity) end end context 'when user has a middle name' do it 'presents name correctly' do expect(form1095b.txt_file).to include( '1 Name of responsible individual-First name, middle name, last name ---- John Michael Smith' ) expect(form1095b.txt_file).to include( '(a) Name of covered individual(s) First name, middle initial, last name ---- John M Smith' ) end end context 'when user has no middle name' do let(:form1095b) { build(:enrollment_system_form1095_b, middle_name: nil) } it 'presents name correctly' do expect(form1095b.txt_file).to include( '1 Name of responsible individual-First name, middle name, last name ---- John Smith' ) expect(form1095b.txt_file).to include( '(a) Name of covered individual(s) First name, middle initial, last name ---- John Smith' ) end end context 'when user has an empty middle name' do let(:form1095b) { build(:enrollment_system_form1095_b, middle_name: '') } it 'presents name correctly' do expect(form1095b.txt_file).to include( '1 Name of responsible individual-First name, middle name, last name ---- John Smith' ) expect(form1095b.txt_file).to include( '(a) Name of covered individual(s) First name, middle initial, last name ---- John Smith' ) end end end end
0
code_files/vets-api-private/spec/models/debts_api
code_files/vets-api-private/spec/models/debts_api/v0/form5655_submission_transaction_log_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe DebtsApi::V0::Form5655Submission, type: :model do let(:user) { create(:user, :loa3) } let(:form5655_submission) { create(:debts_api_form5655_submission, user:, user_uuid: user.uuid) } let(:mock_log) { create(:debt_transaction_log, transactionable: form5655_submission) } before do allow(StatsD).to receive(:increment) end describe '#create_transaction_log_if_needed' do it 'calls DebtTransactionLog.track_waiver when no log exists' do allow(form5655_submission).to receive(:find_transaction_log).and_return(nil) expect(DebtTransactionLog).to receive(:track_waiver) .with(form5655_submission, anything) .and_return(mock_log) form5655_submission.send(:create_transaction_log_if_needed) end it 'returns existing log when one already exists' do allow(form5655_submission).to receive(:find_transaction_log).and_return(mock_log) result = form5655_submission.send(:create_transaction_log_if_needed) expect(result).to eq(mock_log) end end describe '#submit_to_vba' do it 'creates transaction log and marks as submitted' do allow(DebtsApi::V0::Form5655::VBASubmissionJob).to receive(:perform_async) allow(form5655_submission).to receive_messages(user_cache_id: 'cache123', create_transaction_log_if_needed: mock_log) expect(mock_log).to receive(:mark_submitted) form5655_submission.submit_to_vba end end describe '#submit_to_vha' do it 'creates transaction log and marks as submitted' do allow(DebtsApi::V0::Form5655::VHA::VBSSubmissionJob).to receive(:perform_async) allow(DebtsApi::V0::Form5655::VHA::SharepointSubmissionJob).to receive(:perform_in) allow(form5655_submission).to receive_messages(user_cache_id: 'cache123', create_transaction_log_if_needed: mock_log) expect(mock_log).to receive(:mark_submitted) form5655_submission.submit_to_vha end end describe '#register_success' do it 'marks transaction log as completed' do allow(form5655_submission).to receive(:find_transaction_log).and_return(mock_log) expect(mock_log).to receive(:mark_completed) form5655_submission.register_success end end describe '#register_failure' do it 'marks transaction log as failed' do allow(form5655_submission).to receive(:find_transaction_log).and_return(mock_log) expect(mock_log).to receive(:mark_failed) form5655_submission.register_failure('Test error') end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/veteran_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Veteran do subject { described_class.new(params) } let(:params) { attributes_for(:veteran) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include( :date_of_birth, :date_of_death, :gender, :is_deceased, :marital_status, :military_service_number, :place_of_birth, :ssn, :va_claim_number, :military_status ) expect(described_class.permitted_params).to include( race: Preneeds::Race.permitted_params, address: Preneeds::Address.permitted_params, current_name: Preneeds::FullName.permitted_params, service_name: Preneeds::FullName.permitted_params, service_records: [Preneeds::ServiceRecord.permitted_params] ) end describe 'when converting to eoas' do it 'produces a message hash whose keys are ordered' do expect(subject.as_eoas.keys).to eq( %i[ address currentName dateOfBirth dateOfDeath gender race isDeceased maritalStatus militaryServiceNumber placeOfBirth serviceName serviceRecords ssn vaClaimNumber militaryStatus ] ) end it 'removes :dateOfBirth, dateOfDeath and :placeOfBirth if blank' do params[:date_of_birth] = '' params[:date_of_death] = '' params[:place_of_birth] = '' expect(subject.as_eoas.keys).not_to include(:dateOfBirth, :dateOfDeath, :placeOfBirth) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/full_name_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::FullName do subject { described_class.new(params) } let(:params) { attributes_for(:full_name) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include(:first, :last, :maiden, :middle, :suffix) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq(%i[firstName lastName maidenName middleName suffix]) end it 'removes maidenName, middleName, and suffix if blank' do params[:maiden] = '' params[:middle] = '' params[:suffix] = '' expect(subject.as_eoas.keys).not_to include(:maidenName, :middleName, :suffix) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/military_rank_input_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::MilitaryRankInput do context 'with valid attributes' do subject { described_class.new(params) } let(:params) do { branch_of_service: 'AF', start_date: '1947-09-18T00:00:00-04:00', end_date: '1947-09-18T00:00:00-04:00' } end context 'with valid attributes' do it { expect(subject).to be_valid } end context 'with invalid attributes' do it 'requires a branch_of_service' do params.delete(:branch_of_service) expect(subject).not_to be_valid end it 'requires a 2 character long branch_of_service' do params[:branch_of_service] = 'A' expect(subject).not_to be_valid end it 'requires a start_date' do params.delete(:start_date) expect(subject).not_to be_valid end it 'requires a valid ISO 8601 start_date string' do params[:start_date] = '1947-99' expect(subject).not_to be_valid end it 'requires a end_date' do params.delete(:end_date) expect(subject).not_to be_valid end it 'requires a valid ISO 8601 end_date string' do params[:end_date] = '1947-99' expect(subject).not_to be_valid end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/preneed_attachment_hash_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::PreneedAttachmentHash do let(:preneed_attachment_hash) do build(:preneed_attachment_hash) end describe '#get_file' do it 'gets the file from the preneed attachment' do expect(preneed_attachment_hash.get_file.exists?).to be(true) end end describe '#to_attachment' do it 'converts to Preneed::Attachment' do attachment = preneed_attachment_hash.to_attachment expect(attachment.attachment_type.attachment_type_id).to eq(1) expect(attachment.file.filename).to eq(preneed_attachment_hash.get_file.filename) expect(attachment.name).to eq(preneed_attachment_hash.name) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/burial_form_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::BurialForm do subject { described_class.new(params) } let(:params) { attributes_for(:burial_form) } describe 'when setting defaults' do it 'generates a tracking_number' do expect(subject.tracking_number).not_to be_blank end it 'generates sent_time' do expect(subject.sent_time).not_to be_blank end it 'provides vets.gov as the sending_application' do params.delete(:sending_application) expect(subject.sending_application).to eq('vets.gov') end end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq( %i[ applicant applicationStatus attachments claimant currentlyBuriedPersons hasAttachments hasCurrentlyBuried sendingApplication sendingCode sentTime trackingNumber veteran ] ) end it 'removes currentlyBuriedPersons if blank' do params[:currently_buried_persons] = [] expect(subject.as_eoas.keys).not_to include(:currentlyBuriedPersons) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json.except('sentTime', 'trackingNumber', 'hasAttachments')) end end describe 'when validating' do it 'compares a form against the schema' do schema = VetsJsonSchema::SCHEMAS['40-10007'] expect(described_class.validate(schema, described_class.new(params))).to be_empty end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/attachment_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Attachment do let(:attachment) do build(:preneed_attachment_hash).to_attachment end let(:hex) do 'de4761e83497fd19b7bceb3315dc5efb' end describe '#as_eoas' do it 'returns the eoas hash' do allow(SecureRandom).to receive(:hex).and_return(hex) expect(attachment.as_eoas).to eq( attachmentType: { attachmentTypeId: 1 }, dataHandler: { 'inc:Include': '', attributes!: { 'inc:Include': { href: "cid:#{hex}", 'xmlns:inc': 'http://www.w3.org/2004/08/xop/include' } } }, description: 'dd214a.pdf', sendingName: 'vets.gov', sendingSource: 'vets.gov' ) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/cemetery_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Cemetery do context 'with valid attributes' do subject { described_class.new(params) } let(:params) { attributes_for(:cemetery) } let(:other) { described_class.new(attributes_for(:cemetery)) } it 'populates attributes' do expect(described_class.attribute_set).to contain_exactly(:name, :num, :cemetery_type) expect(subject.name).to eq(params[:name]) expect(subject.num).to eq(params[:num]) expect(subject.cemetery_type).to eq(params[:cemetery_type]) end it 'can be compared by name' do expect(subject <=> other).to eq(-1) expect(other <=> subject).to eq(1) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/attachment_type_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::AttachmentType do context 'with valid attributes' do subject { described_class.new(params) } let(:params) { attributes_for(:preneeds_attachment_type) } let(:other) { described_class.new(attributes_for(:preneeds_attachment_type)) } it 'populates attributes' do name_map = described_class.attribute_set expect(name_map).to contain_exactly(:description, :attachment_type_id) expect(subject.attachment_type_id).to eq(params[:attachment_type_id]) expect(subject.description).to eq(params[:description]) end it 'can be compared by description' do expect(subject <=> other).to eq(-1) expect(other <=> subject).to eq(1) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/receive_application_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::ReceiveApplication do context 'with valid attributes' do subject { described_class.new(params) } let(:params) { attributes_for(:receive_application) } it 'populates attributes', run_at: '2017-01-04 03:00:00 EDT' do name_map = described_class.attribute_set expect(name_map).to contain_exactly( :tracking_number, :return_code, :application_uuid, :return_description, :submitted_at ) expect(subject.tracking_number).to eq(params[:tracking_number]) expect(subject.return_code).to eq(params[:return_code]) expect(subject.application_uuid).to eq(params[:application_uuid]) expect(subject.return_description).to eq(params[:return_description]) expect(subject.submitted_at).to eq(Time.zone.now) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/preneed_submission_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::PreneedSubmission, type: :model do subject { build(:preneed_submission) } describe 'when validating' do it 'has a valid factory' do expect(subject).to be_valid end it 'requires a tracking_number' do subject.tracking_number = nil expect(subject).not_to be_valid end it 'requires a return_description' do subject.return_description = nil expect(subject).not_to be_valid end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/service_record_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::ServiceRecord do subject { described_class.new(params) } let(:params) { attributes_for(:service_record) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include( :service_branch, :discharge_type, :highest_rank, :national_guard_state ) expect(described_class.permitted_params).to include(date_range: Preneeds::DateRange.permitted_params) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq( %i[branchOfService dischargeType enteredOnDutyDate highestRank nationalGuardState releaseFromDutyDate] ) end it 'removes enteredOnDutyDate, releaseFromDutyDate, highestRank, and nationalGuardState if blank' do params[:national_guard_state] = '' params[:highest_rank] = '' params[:date_range] = { from: '', to: '' } expect(subject.as_eoas.keys).not_to include( :enteredOnDutyDate, :releaseFromDutyDate, :highestRank, :nationalGuardState ) end end describe 'when converting to json' do # let(:params) { attributes_for :service_record, :for_json_comparison } it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/date_range_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::DateRange do subject { described_class.new(params) } let(:params) { attributes_for(:date_range) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include(:from, :to) end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/currently_buried_person_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::CurrentlyBuriedPerson do subject { described_class.new(params) } let(:params) { attributes_for(:currently_buried_person) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include(:cemetery_number) expect(described_class.permitted_params).to include(name: Preneeds::FullName.permitted_params) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq(%i[cemeteryNumber name]) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/claimant_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Claimant do subject { described_class.new(params) } let(:params) { attributes_for(:claimant) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include( :date_of_birth, :desired_cemetery, :email, :phone_number, :relationship_to_vet, :ssn ) expect(described_class.permitted_params).to include( address: Preneeds::Address.permitted_params, name: Preneeds::FullName.permitted_params ) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq( %i[address dateOfBirth desiredCemetery email name phoneNumber relationshipToVet ssn] ) end it 'removes :email and :phone_number if blank' do params[:email] = '' params[:phone_number] = '' expect(subject.as_eoas.keys).not_to include(:email, :phoneNumber) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/race_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Race do subject { build(:race) } describe '#as_eoas' do it 'returns the right value' do expect(subject.as_eoas).to eq([{ raceCd: 'I' }, { raceCd: 'U' }]) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/applicant_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Applicant do subject { described_class.new(params) } let(:params) { attributes_for(:applicant) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include( :applicant_email, :applicant_phone_number, :applicant_relationship_to_claimant, :completing_reason ) expect(described_class.permitted_params).to include( mailing_address: Preneeds::Address.permitted_params, name: Preneeds::FullName.permitted_params ) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq( %i[ applicantEmail applicantPhoneNumber applicantRelationshipToClaimant completingReason mailingAddress name ] ) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/preneeds/address_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::Address do subject { described_class.new(params) } context 'with US/CAN address' do let(:params) { attributes_for(:address) } it 'specifies the permitted_params' do expect(described_class.permitted_params).to include( :street, :street2, :city, :country, :postal_code, :state ) end describe 'when converting to eoas' do it 'produces an ordered hash' do expect(subject.as_eoas.keys).to eq(%i[address1 address2 city countryCode postalZip state]) end it 'removes address2 if blank' do params[:street2] = '' expect(subject.as_eoas.keys).not_to include(:address2) end end describe 'when converting to json' do it 'converts its attributes from snakecase to camelcase' do camelcased = params.deep_transform_keys { |key| key.to_s.camelize(:lower) } expect(camelcased).to eq(subject.as_json) end end end context 'with foreign address' do let(:params) { attributes_for(:foreign_address) } it 'treats nil state as empty string' do expect(subject.as_eoas[:state]).to eq('') end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/notice_of_disagreement_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::NoticeOfDisagreement, type: :model do let(:guid) { SecureRandom.uuid } let(:form_data) do { stuff: 'things' } end let!(:appeal_submission) { create(:appeal_submission, type_of_appeal: 'SC', submitted_appeal_uuid: guid) } describe 'AppealSubmission association' do let!(:saved_claim_nod) { described_class.create!(guid:, form: form_data.to_json) } it 'has one AppealSubmission' do expect(saved_claim_nod.appeal_submission).to eq appeal_submission end it 'can be accessed from the AppealSubmission' do expect(appeal_submission.saved_claim_nod).to eq saved_claim_nod end end describe 'validation' do let!(:saved_claim_nod) { described_class.new(guid:, form: form_data.to_json) } context 'no validation errors' do it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return([]) expect(saved_claim_nod.validate).to be true end end context 'with validation errors' do let(:validation_errors) { ['error', 'error 2'] } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return(validation_errors) expect(Rails.logger).to receive(:warn).with('SavedClaim: schema validation errors detected for form 10182', guid:, count: 2) expect(saved_claim_nod.validate).to be true end end context 'with JSON validator exception' do let(:exception) { JSON::Schema::ReadFailed.new('location', 'type') } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_raise(exception) expect(Rails.logger).to receive(:warn).with('SavedClaim: form_matches_schema error raised for form 10182', guid:, error: exception.message) expect(saved_claim_nod.validate).to be true end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/form21p530a_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::Form21p530a, type: :model do let(:valid_form_data) { JSON.parse(Rails.root.join('spec', 'fixtures', 'form21p530a', 'valid_form.json').read) } let(:invalid_form_data) do JSON.parse(Rails.root.join('spec', 'fixtures', 'form21p530a', 'invalid_form.json').read) end let(:claim) { described_class.new(form: valid_form_data.to_json) } describe 'validations' do let(:claim) { described_class.new(form: form.to_json) } let(:form) { valid_form_data.dup } context 'with valid form data' do it 'validates successfully' do claim = described_class.new(form: valid_form_data.to_json) expect(claim).to be_valid end end context 'with invalid form data from fixture' do it 'fails validation for multiple reasons' do claim = described_class.new(form: invalid_form_data.to_json) expect(claim).not_to be_valid # Should fail because: # - aptOrUnitNumber exceeds maxLength of 5 # - missing certification signature end end context 'OpenAPI schema validation' do it 'rejects middle name longer than 1 character' do form['veteranInformation']['fullName']['middle'] = 'AB' expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 1') end it 'rejects first name longer than 12 characters' do form['veteranInformation']['fullName']['first'] = 'A' * 13 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 12') end it 'rejects last name longer than 18 characters' do form['veteranInformation']['fullName']['last'] = 'A' * 19 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 18') end it 'rejects invalid SSN format' do form['veteranInformation']['ssn'] = '12345' # Too short expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('pattern') end it 'accepts aptOrUnitNumber up to 5 characters' do form['burialInformation']['recipientOrganization']['address']['aptOrUnitNumber'] = 'A' * 5 expect(claim).to be_valid end it 'rejects aptOrUnitNumber longer than 5 characters' do form['burialInformation']['recipientOrganization']['address']['aptOrUnitNumber'] = 'A' * 6 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 5') end it 'accepts country codes up to 3 characters' do form['burialInformation']['recipientOrganization']['address']['country'] = 'USA' expect(claim).to be_valid end it 'rejects country longer than 3 characters' do form['burialInformation']['recipientOrganization']['address']['country'] = 'USAA' expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 3') end it 'rejects invalid postalCodeExtension format' do form['burialInformation']['recipientOrganization']['address']['postalCodeExtension'] = '12345' # Too long expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('pattern') end it 'requires veteran full name' do form['veteranInformation'].delete('fullName') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires veteran date of birth' do form['veteranInformation'].delete('dateOfBirth') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires veteran date of death' do form['veteranInformation'].delete('dateOfDeath') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end end end describe '#send_confirmation_email' do it 'does not send email (MVP does not include email)' do expect(VANotify::EmailJob).not_to receive(:perform_async) claim.send_confirmation_email end end describe '#business_line' do it 'returns PMC for pension management center' do expect(claim.business_line).to eq('PMC') end end describe '#document_type' do it 'returns 540 for burial/memorial benefits' do expect(claim.document_type).to eq(540) end end describe '#regional_office' do it 'returns Pension Management Center address' do expected_address = [ 'Department of Veterans Affairs', 'Pension Management Center', 'P.O. Box 5365', 'Janesville, WI 53547-5365' ] expect(claim.regional_office).to eq(expected_address) end end describe '#process_attachments!' do it 'queues Lighthouse submission job without attachments' do allow(claim).to receive(:id).and_return(123) expect(Lighthouse::SubmitBenefitsIntakeClaim).to receive(:perform_async).with(123) claim.process_attachments! end end describe '#attachment_keys' do it 'returns empty array (no attachments in MVP)' do expect(claim.attachment_keys).to eq([]) end end describe '#to_pdf' do let(:pdf_path) { '/tmp/test_form.pdf' } before do allow(PdfFill::Filler).to receive(:fill_form).and_return(pdf_path) end it 'generates PDF' do result = claim.to_pdf expect(PdfFill::Filler).to have_received(:fill_form).with(claim, nil, {}) expect(result).to eq(pdf_path) end it 'passes fill_options to the filler' do fill_options = { extras_redesign: true } claim.to_pdf('test-id', fill_options) expect(PdfFill::Filler).to have_received(:fill_form).with(claim, 'test-id', fill_options) end end describe 'FORM constant' do it 'is set to 21P-530a' do expect(described_class::FORM).to eq('21P-530a') end end describe '#metadata_for_benefits_intake' do context 'with all fields present' do it 'returns correct metadata hash' do metadata = claim.metadata_for_benefits_intake expect(metadata).to eq( veteranFirstName: 'John', veteranLastName: 'Doe', fileNumber: '123456789', zipCode: '64037', businessLine: 'PMC' ) end end context 'when vaFileNumber is present' do it 'prefers vaFileNumber over ssn' do form_data = valid_form_data.dup form_data['veteranInformation']['vaFileNumber'] = '12345678' form_data['veteranInformation']['ssn'] = '999999999' claim_with_both = described_class.new(form: form_data.to_json) metadata = claim_with_both.metadata_for_benefits_intake expect(metadata[:fileNumber]).to eq('12345678') end end context 'when vaFileNumber is missing' do it 'falls back to ssn' do form_data = valid_form_data.dup form_data['veteranInformation'].delete('vaFileNumber') form_data['veteranInformation']['ssn'] = '111223333' claim_without_va_file = described_class.new(form: form_data.to_json) metadata = claim_without_va_file.metadata_for_benefits_intake expect(metadata[:fileNumber]).to eq('111223333') end end context 'when zipCode is missing' do it 'defaults to 00000 when recipientOrganization address postalCode is missing' do form_data = valid_form_data.dup form_data['burialInformation']['recipientOrganization']['address'].delete('postalCode') claim_without_zip = described_class.new(form: form_data.to_json) metadata = claim_without_zip.metadata_for_benefits_intake expect(metadata[:zipCode]).to eq('00000') end it 'defaults to 00000 when recipientOrganization address is missing' do form_data = valid_form_data.dup form_data['burialInformation']['recipientOrganization'].delete('address') claim_without_address = described_class.new(form: form_data.to_json) metadata = claim_without_address.metadata_for_benefits_intake expect(metadata[:zipCode]).to eq('00000') end it 'defaults to 00000 when recipientOrganization is missing' do form_data = valid_form_data.dup form_data['burialInformation'].delete('recipientOrganization') claim_without_org = described_class.new(form: form_data.to_json) metadata = claim_without_org.metadata_for_benefits_intake expect(metadata[:zipCode]).to eq('00000') end end it 'always includes businessLine from business_line method' do metadata = claim.metadata_for_benefits_intake expect(metadata[:businessLine]).to eq('PMC') expect(metadata[:businessLine]).to eq(claim.business_line) end end describe 'private methods' do describe '#organization_name' do it 'returns recipient organization name when present' do expect(claim.send(:organization_name)).to eq('Missouri Veterans Commission') end it 'returns nameOfStateCemeteryOrTribalOrganization when recipient name is missing' do form_data = valid_form_data.dup form_data['burialInformation'].delete('recipientOrganization') claim_without_recipient = described_class.new(form: form_data.to_json) expect(claim_without_recipient.send(:organization_name)).to eq('Missouri State Veterans Cemetery') end end describe '#veteran_name' do it 'returns full name when present' do expect(claim.send(:veteran_name)).to eq('John Doe') end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/dependency_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'dependents/error_classes' RSpec.describe SavedClaim::DependencyClaim do subject { create(:dependency_claim) } let(:subject_v2) { create(:dependency_claim_v2) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:adopted_child) { build(:adopted_child_lives_with_veteran) } let(:adopted_child_v2) { build(:adopted_child_lives_with_veteran_v2) } let(:form_674_only) { build(:form_674_only) } let(:form_674_only_v2) { build(:form_674_only_v2) } let(:doc_type) { '148' } let(:va_file_number) { subject.parsed_form['veteran_information']['va_file_number'] } let(:va_file_number_v2) { subject_v2.parsed_form['veteran_information']['va_file_number'] } let(:va_file_number_with_payload) do { 'veteran_information' => { 'birth_date' => '1809-02-12', 'full_name' => { 'first' => 'WESLEY', 'last' => 'FORD', 'middle' => nil }, 'ssn' => va_file_number, 'va_file_number' => va_file_number } } end let(:va_file_number_with_payload_v2) do { 'veteran_information' => { 'birth_date' => '1809-02-12', 'full_name' => { 'first' => 'WESLEY', 'last' => 'FORD', 'middle' => nil }, 'ssn' => va_file_number_v2, 'va_file_number' => va_file_number_v2 } } end let(:file_path) { "tmp/pdfs/686C-674_#{subject.id}_final.pdf" } let(:file_path_v2) { "tmp/pdfs/686C-674-V2_#{subject_v2.id}_final.pdf" } before do # Mock expensive PDF operations to avoid file I/O allow(PdfFill::Filler).to receive(:fill_form).and_return('tmp/pdfs/mock_form_final.pdf') allow(File).to receive(:rename) allow(Common::FileHelpers).to receive(:delete_file_if_exists) datestamp_instance = instance_double(PDFUtilities::DatestampPdf, run: 'tmp/pdfs/mock_processed.pdf') allow(PDFUtilities::DatestampPdf).to receive(:new).and_return(datestamp_instance) end context 'when there is an error with PdfFill::Filler' do let(:error) { StandardError.new('PDF Fill Error') } before { allow(PdfFill::Filler).to receive(:fill_form).and_raise(error) } it 'raises a StandardError and tracks the error when PdfFill::Filler fails' do expect(subject.monitor).to receive(:track_to_pdf_failure).with(error, '686C-674') expect { subject.to_pdf(form_id: '686C-674') }.to raise_error(error) end end describe 'both forms' do context 'processing a v1 payload' do subject { described_class.new(form: all_flows_payload.to_json) } describe '#formatted_686_data' do it 'returns all data for 686 submissions' do formatted_data = subject.formatted_686_data(va_file_number_with_payload) expect(formatted_data).to include(:veteran_information) end end describe '#formatted_674_data' do it 'returns all data for 674 submissions' do formatted_data = subject.formatted_674_data(va_file_number_with_payload) expect(formatted_data).to include(:dependents_application) expect(formatted_data[:dependents_application]).to include(:student_name_and_ssn) end end describe '#submittable_686?' do it 'checks if there are 686 flows to process' do expect(subject.submittable_686?).to be(true) end end describe '#submittable_674?' do it 'checks if there are 674 to process' do expect(subject.submittable_674?).to be(true) end end end context 'processing a v2 payload' do subject { described_class.new(form: all_flows_payload_v2.to_json, use_v2: true) } describe '#formatted_686_data' do it 'returns all data for 686 submissions' do formatted_data = subject.formatted_686_data(va_file_number_with_payload_v2) expect(formatted_data).to include(:veteran_information) end end describe '#formatted_674_data' do it 'returns all data for 674 submissions' do formatted_data = subject.formatted_674_data(va_file_number_with_payload_v2) expect(formatted_data).to include(:dependents_application) expect(formatted_data[:dependents_application]).to include(:student_information) end end describe '#submittable_686?' do it 'checks if there are 686 flows to process' do expect(subject.submittable_686?).to be(true) end end describe '#submittable_674?' do it 'checks if there are 674 to process' do expect(subject.submittable_674?).to be(true) end end end end describe '674 form only' do context 'processing a v1 payload' do subject { described_class.new(form: form_674_only.to_json) } describe '#submittable_686?' do it 'returns false if there is no 686 to process' do expect(subject.submittable_686?).to be(false) end end end context 'processing a v2 payload' do subject { described_class.new(form: form_674_only_v2.to_json, use_v2: true) } describe '#submittable_686?' do it 'returns false if there is no 686 to process' do expect(subject.submittable_686?).to be(false) end end end end describe 'with adopted child' do context 'processing a v1 payload' do subject { described_class.new(form: adopted_child.to_json) } describe '#submittable_674?' do it 'returns false if there is no 674 to process' do expect(subject.submittable_674?).to be(false) end end describe '#regional_office' do it 'expects to be empty always' do expect(subject.regional_office).to eq([]) end end end context 'processing a v2 payload' do subject { described_class.new(form: adopted_child_v2.to_json, use_v2: true) } describe '#submittable_674?' do it 'returns false if there is no 674 to process' do expect(subject.submittable_674?).to be(false) end end describe '#regional_office' do it 'expects to be empty always' do expect(subject.regional_office).to eq([]) end end end end context 'v2 form on and vets json schema enabled' do subject { described_class.new(form: all_flows_payload_v2.to_json, use_v2: true) } before do allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) allow(Flipper).to receive(:enabled?).with(:dependents_bypass_schema_validation).and_return(false) end it 'has a form id of 686C-674-V2' do expect(subject.form_id).to eq('686C-674-V2') end context 'after create' do it 'tracks pdf overflow' do allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) allow(StatsD).to receive(:increment) subject.save! tags = ['form_id:686C-674-V2'] expect(StatsD).to have_received(:increment).with('saved_claim.pdf.overflow', tags:) expect(StatsD).to have_received(:increment).with('saved_claim.create', tags: tags + ['doctype:148']) end it 'calls PdfFill::Filler.fill_form during PDF overflow tracking' do allow(StatsD).to receive(:increment) expect(PdfFill::Filler).to receive(:fill_form).at_least(:once) subject.save! end end context 'with bad schema data' do before do subject.parsed_form['statement_of_truth_signature'] = nil subject.form = subject.parsed_form.to_json end it 'rejects the bad payload' do subject.validate expect(subject).not_to be_valid end end end context 'v2 form and vets json schema disabled' do subject { described_class.new(form: all_flows_payload_v2.to_json, use_v2: true) } before do allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) allow(Flipper).to receive(:enabled?).with(:dependents_bypass_schema_validation).and_return(true) end it 'has a form id of 686C-674-V2' do expect(subject.form_id).to eq('686C-674-V2') end context 'after create' do it 'tracks pdf overflow' do allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) allow(StatsD).to receive(:increment) subject.save! tags = ['form_id:686C-674-V2'] expect(StatsD).to have_received(:increment).with('saved_claim.pdf.overflow', tags:) expect(StatsD).to have_received(:increment).with('saved_claim.create', tags: tags + ['doctype:148']) end it 'ensures PDF tracking works with schema validation disabled' do allow(StatsD).to receive(:increment) expect(PdfFill::Filler).to receive(:fill_form).at_least(:once) subject.save! end end context 'with bad schema data' do before do subject.parsed_form['statement_of_truth_signature'] = nil subject.form = subject.parsed_form.to_json end it 'accepts the bad payload' do subject.validate expect(subject).to be_valid end end end describe '#send_failure_email' do let(:email) { 'test@example.com' } let(:today_string) { 'August 15, 2025' } let(:confirmation_number) { subject.guid } let(:first_name) { 'JOHN' } let(:expected_personalisation) do { 'first_name' => first_name, 'date_submitted' => today_string, 'confirmation_number' => confirmation_number } end before do allow(Dependents::Form686c674FailureEmailJob).to receive(:perform_async) subject.parsed_form['dependents_application']['veteran_information']['full_name']['first'] = first_name.downcase end context 'when both 686c and 674 forms are submittable' do before do allow_any_instance_of(SavedClaim::DependencyClaim) .to receive_messages(submittable_686?: true, submittable_674?: true) end it 'sends a combo email with the correct parameters', run_at: 'Thu, 15 Aug 2025 15:30:00 GMT' do expect(Dependents::Form686c674FailureEmailJob) .to receive(:perform_async) .with( subject.id, email, Settings.vanotify.services.va_gov.template_id.form21_686c_674_action_needed_email, expected_personalisation ) subject.send_failure_email(email) end end context 'when only 686c form is submittable' do before do allow_any_instance_of(SavedClaim::DependencyClaim) .to receive_messages(submittable_686?: true, submittable_674?: false) end it 'sends a 686c email with the correct parameters', run_at: 'Thu, 15 Aug 2025 15:30:00 GMT' do expect(Dependents::Form686c674FailureEmailJob) .to receive(:perform_async) .with( subject.id, email, Settings.vanotify.services.va_gov.template_id.form21_686c_action_needed_email, expected_personalisation ) subject.send_failure_email(email) end end context 'when only 674 form is submittable' do before do allow_any_instance_of(SavedClaim::DependencyClaim) .to receive_messages(submittable_686?: false, submittable_674?: true) end it 'sends a 674 email with the correct parameters', run_at: 'Thu, 15 Aug 2025 15:30:00 GMT' do expect(Dependents::Form686c674FailureEmailJob) .to receive(:perform_async) .with( subject.id, email, Settings.vanotify.services.va_gov.template_id.form21_674_action_needed_email, expected_personalisation ) subject.send_failure_email(email) end end context 'when neither form is submittable' do before do allow_any_instance_of(SavedClaim::DependencyClaim) .to receive_messages(submittable_686?: false, submittable_674?: false) allow(Rails.logger).to receive(:error) end it 'logs an error and does not send email', run_at: 'Thu, 15 Aug 2025 15:30:00 GMT' do expect(Rails.logger).to receive(:error).with('Email template cannot be assigned for SavedClaim', saved_claim_id: subject.id) expect(Dependents::Form686c674FailureEmailJob).not_to receive(:perform_async) subject.send_failure_email(email) end end context 'when email is blank' do it 'does not send an email', run_at: 'Thu, 15 Aug 2025 15:30:00 GMT' do expect(Dependents::Form686c674FailureEmailJob).not_to receive(:perform_async) subject.send_failure_email('') end end context 'when overflow tracking fails' do let(:standard_error) { StandardError.new('test error') } let(:claim_data) { build(:dependency_claim).attributes } before do allow(Flipper).to receive(:enabled?) .with(:saved_claim_pdf_overflow_tracking).and_return(true) allow(PdfFill::Filler).to receive(:fill_form).and_return('fake_path.pdf') allow(Common::FileHelpers).to receive(:delete_file_if_exists).and_raise(standard_error) end it 'has the monitor track the failure' do claim = SavedClaim::DependencyClaim.new(claim_data) expect(claim.monitor).to receive(:track_pdf_overflow_tracking_failure).with(standard_error) claim.save! end end context 'when address is not present' do let(:claim_data) { build(:dependency_claim).attributes } it 'flags an error if the address is not present' do claim = SavedClaim::DependencyClaim.new(claim_data) claim.parsed_form['dependents_application']['veteran_contact_information'].delete('veteran_address') expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:parsed_form) expect(claim.errors[:parsed_form]).to include("Veteran address can't be blank") end end end context 'when 686 data is invalid' do let(:claim_data) { build(:dependency_claim).attributes } let(:claim) { SavedClaim::DependencyClaim.new(claim_data) } it 'flags an error when the veteran ssn is not present' do claim.parsed_form['veteran_information'].delete('ssn') claim.valid?(:run_686_form_jobs) expect(claim.errors.attribute_names).to include(:parsed_form) expect(claim.errors[:parsed_form]).to include("SSN can't be blank") end it 'flags an error when dependent application data is not present' do claim.parsed_form.delete('dependents_application') claim.valid?(:run_686_form_jobs) expect(claim.errors.attribute_names).to include(:parsed_form) expect(claim.errors[:parsed_form]).to include("Dependent application can't be blank") end end context 'when determining document_type' do describe '#document_type' do it 'returns the correct document type' do expect(subject.document_type).to eq 148 end end end context 'sending submitted email' do context 'when form 686 only' do subject { described_class.new(form: adopted_child.to_json) } it 'delivers a 686 submitted email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:submitted686) expect(subject.monitor).to receive(:track_send_submitted_email_success).with(nil) subject.send_submitted_email(nil) end end context 'when form 674 only' do subject { described_class.new(form: form_674_only.to_json) } it 'delivers a 674 submitted email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:submitted674) expect(subject.monitor).to receive(:track_send_submitted_email_success).with(nil) subject.send_submitted_email(nil) end end context 'when form 686 and 674' do subject { described_class.new(form: all_flows_payload.to_json) } it 'delivers a combo submitted email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:submitted686c674) expect(subject.monitor).to receive(:track_send_submitted_email_success).with(nil) subject.send_submitted_email(nil) end end context 'when neither 686 nor 674 (an error)' do subject { described_class.new } it 'delivers a combo submitted email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(subject.monitor).to receive(:track_unknown_claim_type).with(kind_of(StandardError)) expect(notification_email).to receive(:deliver).with(:submitted686c674) # Not sure why this is being done, but it is expect(subject.monitor).to receive(:track_send_submitted_email_success).with(nil) subject.send_submitted_email(nil) end end context 'when an error occurs while sending the email' do subject { described_class.new } let(:standard_error) { StandardError.new('test error') } before do allow(Dependents::NotificationEmail).to receive(:new).and_raise(standard_error) end it 'tracks the error' do expect(subject.monitor).to receive(:track_send_submitted_email_failure).with(standard_error, nil) subject.send_submitted_email(nil) end end end context 'sending received email' do context 'when form 686 only' do subject { described_class.new(form: adopted_child.to_json) } it 'delivers a 686 received email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:received686) expect(subject.monitor).to receive(:track_send_received_email_success).with(nil) subject.send_received_email(nil) end end context 'when form 674 only' do subject { described_class.new(form: form_674_only.to_json) } it 'delivers a 674 received email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:received674) expect(subject.monitor).to receive(:track_send_received_email_success).with(nil) subject.send_received_email(nil) end end context 'when form 686 and 674' do subject { described_class.new(form: all_flows_payload.to_json) } it 'delivers a combo received email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(notification_email).to receive(:deliver).with(:received686c674) expect(subject.monitor).to receive(:track_send_received_email_success).with(nil) subject.send_received_email(nil) end end context 'when neither 686 nor 674 (an error)' do subject { described_class.new } it 'delivers a combo received email' do notification_email = instance_double(Dependents::NotificationEmail) expect(Dependents::NotificationEmail) .to receive(:new).with(subject.id, nil) .and_return(notification_email) expect(subject.monitor).to receive(:track_unknown_claim_type).with(kind_of(StandardError)) expect(notification_email).to receive(:deliver).with(:received686c674) # Not sure why this is being done, but it is expect(subject.monitor).to receive(:track_send_received_email_success).with(nil) subject.send_received_email(nil) end end context 'when an error occurs while sending the email' do subject { described_class.new } let(:standard_error) { StandardError.new('test error') } before do allow(Dependents::NotificationEmail).to receive(:new).and_raise(standard_error) end it 'tracks the error' do expect(subject.monitor).to receive(:track_send_received_email_failure).with(standard_error, nil) subject.send_received_email(nil) end end context 'when veteran_information is missing' do let(:no_veteran_claim) { create(:dependency_claim_no_vet_information) } before do allow(PdfFill::Filler).to receive(:fill_form).and_call_original subject_v2.parsed_form.delete('veteran_information') subject_v2.parsed_form['dependents_application'].delete('veteran_information') end it 'raises an error in the PDF filler' do expect { no_veteran_claim.to_pdf(form_id: '686C-674-V2') }.to raise_error(Dependents::ErrorClasses::MissingVeteranInfoError) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/form212680_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::Form212680, type: :model do let(:claim) { build(:form212680) } describe 'FORM constant' do it 'is set to 21-2680' do expect(described_class::FORM).to eq('21-2680') end end describe '#regional_office' do it 'returns Pension Management Center address' do expect(claim.regional_office).to eq([ 'Department of Veterans Affairs', 'Pension Management Center', 'P.O. Box 5365', 'Janesville, WI 53547-5365' ]) end end describe '#business_line' do it 'returns PMC for Pension Management Center' do expect(claim.business_line).to eq('PMC') end end describe '#document_type' do it 'returns 540 for Aid and Attendance/Housebound' do expect(claim.document_type).to eq(540) end end describe '#attachment_keys' do it 'returns empty frozen array' do expect(claim.attachment_keys).to eq([]) expect(claim.attachment_keys).to be_frozen end end describe '#to_pdf' do let(:pdf_path) { '/tmp/test_form.pdf' } let(:stamped_pdf_path) { '/tmp/test_form_stamped.pdf' } let(:parsed_form_data) do { 'veteranSignature' => { 'signature' => 'John Doe' } } end before do allow(PdfFill::Filler).to receive(:fill_form).and_return(pdf_path) allow(PdfFill::Forms::Va212680).to receive(:stamp_signature).and_return(stamped_pdf_path) allow(claim).to receive(:parsed_form).and_return(parsed_form_data) end it 'generates PDF and stamps the signature' do result = claim.to_pdf expect(PdfFill::Filler).to have_received(:fill_form).with(claim, nil, {}) expect(PdfFill::Forms::Va212680).to have_received(:stamp_signature).with(pdf_path, parsed_form_data) expect(result).to eq(stamped_pdf_path) end it 'passes file_name to the filler' do claim.to_pdf('custom-file-name') expect(PdfFill::Filler).to have_received(:fill_form).with(claim, 'custom-file-name', {}) end it 'passes fill_options to the filler' do fill_options = { extras_redesign: true } claim.to_pdf('test-id', fill_options) expect(PdfFill::Filler).to have_received(:fill_form).with(claim, 'test-id', fill_options) end it 'returns the stamped PDF path' do result = claim.to_pdf expect(result).to eq(stamped_pdf_path) end end describe '#generate_prefilled_pdf' do let(:pdf_path) { '/tmp/generated_form.pdf' } before do allow(claim).to receive(:to_pdf).and_return(pdf_path) allow(claim).to receive(:update_metadata_with_pdf_generation) end it 'generates a PDF' do claim.generate_prefilled_pdf expect(claim).to have_received(:to_pdf).with(no_args) end it 'updates metadata after PDF generation' do claim.generate_prefilled_pdf expect(claim).to have_received(:update_metadata_with_pdf_generation) end it 'returns the generated PDF path' do result = claim.generate_prefilled_pdf expect(result).to eq(pdf_path) end end describe '#download_instructions' do before do allow(Settings).to receive(:hostname).and_return('https://www.va.gov') end it 'returns download instructions hash' do instructions = claim.download_instructions expect(instructions[:title]).to eq('Next Steps: Get Physician to Complete Form') expect(instructions[:form_number]).to eq('21-2680') expect(instructions[:upload_url]).to eq('https://www.va.gov/upload-supporting-documents') expect(instructions[:steps]).to be_an(Array) expect(instructions[:steps].length).to eq(7) end it 'includes regional office in instructions' do instructions = claim.download_instructions expect(instructions[:regional_office]).to include('Pension Management Center') end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/veteran_readiness_employment_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' require_relative '../../../modules/claims_api/spec/support/fake_vbms' require 'claims_api/vbms_uploader' RSpec.describe SavedClaim::VeteranReadinessEmploymentClaim do let(:user_object) { create(:evss_user, :loa3) } let(:user_struct) do OpenStruct.new( edipi: user_object.edipi, participant_id: user_object.participant_id, pid: user_object.participant_id, birth_date: user_object.birth_date, ssn: user_object.ssn, vet360_id: user_object.vet360_id, loa3?: true, icn: user_object.icn, uuid: user_object.uuid, first_name: user_object.first_name, va_profile_email: user_object.va_profile_email ) end let(:encrypted_user) { KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json) } let(:user) { OpenStruct.new(JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_user))) } let(:claim) { create(:veteran_readiness_employment_claim) } before do allow_any_instance_of(RES::Ch31Form).to receive(:submit).and_return(true) end describe '#form_id' do it 'returns the correct form ID' do expect(claim.form_id).to eq('28-1900-V2') end end describe '#after_create_metrics' do it 'increments StatsD saved_claim.create' do allow(StatsD).to receive(:increment) claim.save! tags = ['form_id:28-1900-V2', 'doctype:10'] expect(StatsD).to have_received(:increment).with('saved_claim.create', { tags: }) end end describe '#add_claimant_info' do it 'adds veteran information' do claim.add_claimant_info(user_object) claimant_keys = %w[fullName dob pid edipi vet360ID regionalOffice regionalOfficeName stationId VAFileNumber ssn] form_data = { 'fullName' => { 'first' => 'First', 'middle' => 'Middle', 'last' => 'Last', 'suffix' => 'III' }, 'dob' => '1986-05-06' } expect(claim.parsed_form['veteranInformation']).to include(form_data) expect(claim.parsed_form['veteranInformation']).to include(*claimant_keys) end it 'does not obtain va_file_number' do people_service_object = double('people_service') allow(people_service_object).to receive(:find_person_by_participant_id) allow(BGS::People::Request).to receive(:new) { people_service_object } claim.add_claimant_info(user_object) expect(claim.parsed_form['veteranInformation']).to include('VAFileNumber' => nil) end end describe '#send_email' do let(:notification_email) { double('notification_email') } before do allow(VRE::NotificationEmail).to receive(:new).with(claim.id).and_return(notification_email) end context 'when email_type is a confirmation type' do it 'sends VBMS confirmation email' do expect(notification_email).to receive(:deliver).with( SavedClaim::VeteranReadinessEmploymentClaim::CONFIRMATION_EMAIL_TEMPLATES[:confirmation_vbms] ) claim.send_email(:confirmation_vbms) end it 'sends Lighthouse confirmation email' do expect(notification_email).to receive(:deliver).with( SavedClaim::VeteranReadinessEmploymentClaim::CONFIRMATION_EMAIL_TEMPLATES[:confirmation_lighthouse] ) claim.send_email(:confirmation_lighthouse) end end context 'when email_type is not a confirmation type' do it 'sends error email' do expect(notification_email).to receive(:deliver).with( SavedClaim::VeteranReadinessEmploymentClaim::ERROR_EMAIL_TEMPLATE ) claim.send_email(:error) end end end describe '#send_to_vre' do it 'propagates errors from send_to_lighthouse!' do allow(claim).to receive(:process_attachments!).and_raise(StandardError, 'Attachment error') expect do claim.send_to_lighthouse!(user_object) end.to raise_error(StandardError, 'Attachment error') end context 'when VBMS response is VBMSDownForMaintenance' do before do allow(OpenSSL::PKCS12).to receive(:new).and_return(double.as_null_object) @vbms_client = FakeVBMS.new allow(VBMS::Client).to receive(:from_env_vars).and_return(@vbms_client) end it 'calls #send_to_lighthouse!' do expect(claim).to receive(:send_to_lighthouse!) claim.send_to_vre(user_object) end it 'does not raise an error' do allow(claim).to receive(:send_to_lighthouse!) expect { claim.send_to_vre(user_object) }.not_to raise_error end end context 'when VBMS upload is successful' do before { expect(ClaimsApi::VBMSUploader).to receive(:new) { OpenStruct.new(upload!: {}) } } context 'submission to VRE' do before do # As the PERMITTED_OFFICE_LOCATIONS constant at # the top of: app/models/saved_claim/veteran_readiness_employment_claim.rb gets changed, you # may need to change this mock below and maybe even move it into different 'it' # blocks if you need to test different routing offices expect_any_instance_of(BGS::RORoutingService).to receive(:get_regional_office_by_zip_code).and_return( { regional_office: { number: '325' } } ) end it 'sends confirmation email' do allow(Flipper).to receive(:enabled?) .with(:vre_use_new_vfs_notification_library) .and_return(false) expect(claim).to receive(:send_vbms_lighthouse_confirmation_email) .with('VBMS', 'confirmation_vbms_email_template_id') claim.send_to_vre(user_object) end end # We want all submission to go through with RES context 'non-submission to VRE' do context 'flipper enabled' do it 'stops submission if location is not in list' do expect_any_instance_of(RES::Ch31Form).to receive(:submit) claim.add_claimant_info(user_object) claim.send_to_vre(user_object) end end end end context 'when user has no PID' do let(:user_object) { create(:unauthorized_evss_user) } it 'PDF is sent to Central Mail and not VBMS' do Flipper.disable(:vre_use_new_vfs_notification_library) expect(claim).to receive(:process_attachments!) expect(claim).to receive(:send_to_lighthouse!).with(user_object).once.and_call_original expect(claim).to receive(:send_vbms_lighthouse_confirmation_email) expect(claim).not_to receive(:upload_to_vbms) expect(VeteranReadinessEmploymentMailer).to receive(:build).with( user_object.participant_id, 'VRE.VBAPIT@va.gov', true ).and_call_original claim.send_to_vre(user_object) end end end describe '#regional_office' do it 'returns an empty array' do expect(claim.regional_office).to be_empty end end describe '#send_vbms_lighthouse_confirmation_email' do let(:user) do OpenStruct.new( edipi: '1007697216', participant_id: '600061742', first_name: 'WESLEY', va_profile_email: 'test@example.com', flipper_id: 'test-user-id' ) end context 'Legacy notification strategy' do before do allow(Flipper).to receive(:enabled?) .with(:vre_use_new_vfs_notification_library) .and_return(false) end it 'calls the VA notify email job' do expect(VANotify::EmailJob).to receive(:perform_async).with( claim.email, 'ch31_vbms_fake_template_id', { 'date' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => claim.parsed_form['veteranInformation']['fullName']['first'] } ) claim.send_vbms_lighthouse_confirmation_email('VBMS', 'ch31_vbms_fake_template_id') end end end describe '#check_form_v2_validations' do ['', [], nil, {}].each do |address| context "with empty #{address} input" do describe 'address validation' do it 'accepts empty address format as not required' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = address claim_data['newAddress'] = address claim.form = claim_data.to_json expect(claim).to be_valid end end end end context 'when address is not empty' do let(:claim) { build(:veteran_readiness_employment_claim) } it 'passes validation with only street and city' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'street' => '123 Main St', 'city' => 'Anytown' } claim_data['newAddress'] = { 'street' => '456 Elm St', 'city' => 'Othertown' } claim.form = claim_data.to_json expect(claim).to be_valid end it 'passes validation when only one address object is present' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'street' => '123 Main St', 'city' => 'Anytown' } claim.form = claim_data.to_json expect(claim).to be_valid end it 'fails validation when one address object is missing street' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'country' => 'USA', 'city' => 'Anytown', 'state' => 'NY', 'postalCode' => '12345' } claim.form = claim_data.to_json expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranAddress/street') end it 'fails validation when street is missing' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'country' => 'USA', 'city' => 'Anytown', 'state' => 'NY', 'postalCode' => '12345' } claim_data['newAddress'] = { 'country' => 'USA', 'city' => 'Othertown', 'state' => 'CA', 'postalCode' => '67890' } claim.form = claim_data.to_json expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranAddress/street') expect(claim.errors.attribute_names).to include(:'/newAddress/street') end it 'fails validation when city is missing' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'country' => 'USA', 'street' => '123 Main St', 'state' => 'NY', 'postalCode' => '12345' } claim_data['newAddress'] = { 'country' => 'USA', 'street' => '456 Elm St', 'state' => 'CA', 'postalCode' => '67890' } claim.form = claim_data.to_json expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranAddress/city') expect(claim.errors.attribute_names).to include(:'/newAddress/city') end it 'fails validation when fileds are longer than allowed' do claim_data = JSON.parse(claim.form) claim_data['veteranAddress'] = { 'country' => 'USA', 'city' => 'A' * 101, 'street' => '123 Main St', 'state' => 'N' * 101, 'postalCode' => '12345' } claim_data['newAddress'] = { 'country' => 'USA', 'city' => 'O' * 101, 'street' => '456 Elm St', 'state' => 'C' * 101, 'postalCode' => '67890' } claim.form = claim_data.to_json expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranAddress/city') expect(claim.errors.attribute_names).to include(:'/veteranAddress/state') expect(claim.errors.attribute_names).to include(:'/newAddress/city') expect(claim.errors.attribute_names).to include(:'/newAddress/state') end # ['1', '123456', '123456789', 'a' * 5].each do |postal_code| # context 'postal code is not XXXXX or XXXXX-XXXX format' do # it 'fails validation' do # claim = build(:new_veteran_readiness_employment_claim, postal_code:) # expect(claim).not_to be_valid # expect(claim.errors.attribute_names).to include(:'/veteranAddress/postalCode') # expect(claim.errors.attribute_names).to include(:'/veteranAddress/postalCode') # end # end # end end ['USA', 'United States'].each do |country| context "with #{country} format" do let(:claim) { build(:veteran_readiness_employment_claim, country:) } describe 'country validation' do it 'accepts valid country format' do expect(claim).to be_valid end it 'validates other fields independently of country format' do claim_data = JSON.parse(claim.form) claim_data['veteranInformation']['fullName'] = {} # Invalid name claim.form = claim_data.to_json expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/first') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/last') end end end end ['', ' ', nil].each do |invalid_input| context 'when required field is empty' do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, email: invalid_input, is_moving: invalid_input, years_of_ed: invalid_input, first: invalid_input, last: invalid_input, dob: invalid_input, privacyAgreementAccepted: invalid_input) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/email') expect(claim.errors.attribute_names).to include(:'/isMoving') expect(claim.errors.attribute_names).to include(:'/yearsOfEducation') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/first') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/last') expect(claim.errors.attribute_names).to include(:'/veteranInformation/dob') end end end [0, true, ['data']].each do |invalid_type| context "when string field receives #{invalid_type} data type" do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, main_phone: invalid_type, cell_phone: invalid_type, international_number: invalid_type, email: invalid_type, years_of_ed: invalid_type, first: invalid_type, middle: invalid_type, last: invalid_type, dob: invalid_type) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/mainPhone') expect(claim.errors.attribute_names).to include(:'/cellPhone') expect(claim.errors.attribute_names).to include(:'/internationalNumber') expect(claim.errors.attribute_names).to include(:'/email') expect(claim.errors.attribute_names).to include(:'/yearsOfEducation') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/first') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/middle') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/last') expect(claim.errors.attribute_names).to include(:'/veteranInformation/dob') end end end ['true', 1, 0, [], nil].each do |invalid_type| context "when isMoving receives #{invalid_type} data type" do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, is_moving: invalid_type) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/isMoving') end end end context 'when name field is allowed length' do it 'passes validation' do name = 'a' * 30 claim = build(:veteran_readiness_employment_claim, first: name, middle: name, last: name) expect(claim).to be_valid end end context 'when name field is too long' do it 'fails validation' do long_name = 'a' * 31 claim = build(:veteran_readiness_employment_claim, first: long_name, middle: long_name, last: long_name) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/first') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/middle') expect(claim.errors.attribute_names).to include(:'/veteranInformation/fullName/last') end end context 'when email field is allowed length' do it 'passes validation' do email = "#{'a' * 244}@example.com" claim = build(:veteran_readiness_employment_claim, email:) expect(claim).to be_valid end end context 'when email field is too long' do it 'fails validation' do email = "#{'a' * 245}@example.com" claim = build(:veteran_readiness_employment_claim, email:) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/email') end end ['email.com', '@email.com', 'email', '@.com'].each do |email| context 'when email field is not properly formatted' do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, email:) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/email') end end end ['1', '123456789', '12345678901', 'a' * 10].each do |invalid_phone| context 'when phone field is not 10 digits' do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, main_phone: invalid_phone, cell_phone: invalid_phone) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/mainPhone') expect(claim.errors.attribute_names).to include(:'/cellPhone') end end end %w[10-30-1990 30-10-1990 90-10-30 1990-10-1 1990-9-9].each do |invalid_dob| context 'when dob field does not match YYYY-MM-DD format' do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, dob: invalid_dob) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/veteranInformation/dob') end end end end ['true', 1, 0, [], nil].each do |invalid_type| context "when privacyAgreementAccepted receives #{invalid_type} data type" do it 'fails validation' do claim = build(:veteran_readiness_employment_claim, privacyAgreementAccepted: invalid_type) expect(claim).not_to be_valid expect(claim.errors.attribute_names).to include(:'/privacyAgreementAccepted') end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/caregivers_assistance_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::CaregiversAssistanceClaim do describe 'schema' do it 'is deep frozen' do expect do VetsJsonSchema::SCHEMAS['10-10CG']['title'] = 'foo' end.to raise_error(FrozenError) expect(VetsJsonSchema::SCHEMAS['10-10CG']['title']).to eq( 'Application for Comprehensive Assistance for Family Caregivers Program (10-10CG)' ) end end describe '#to_pdf' do let(:claim) { build(:caregivers_assistance_claim) } it 'renders unicode chars correctly' do unicode = 'name’' claim.parsed_form['veteran']['fullName']['first'] = unicode pdf_file = claim.to_pdf(sign: true) expect(PdfFill::Filler::UNICODE_PDF_FORMS.get_fields(pdf_file).map(&:value).find do |val| val == unicode end).to eq(unicode) File.delete(pdf_file) end it 'calls PdfFill::Filler#fill_form' do expect(PdfFill::Filler).to receive(:fill_form).with(claim, claim.guid).once.and_return(:expected_file_paths) expect(claim.to_pdf).to eq(:expected_file_paths) end context 'passes arguments to PdfFill::Filler#fill_form' do it 'converts to pdf with the file name alone' do expect(PdfFill::Filler).to receive( :fill_form ).with( claim, 'my_other_filename' ).once.and_return(:expected_file_paths) # Calling with only filename claim.to_pdf('my_other_filename') end it 'converts to pdf with the options alone' do expect(PdfFill::Filler).to receive( :fill_form ).with( claim, claim.guid, save: true ).once.and_return(:expected_file_paths) # Calling with only options claim.to_pdf(save: true) end it 'converts to pdf with the filename and options' do expect(PdfFill::Filler).to receive( :fill_form ).with( claim, 'my_other_filename', save: false ).once.and_return(:expected_file_paths) # Calling with filename and options claim.to_pdf('my_other_filename', save: false) end end context 'errors' do let(:error_message) { 'fill form error' } before do allow(PdfFill::Filler).to receive(:fill_form).and_raise(StandardError, error_message) allow(Rails.logger).to receive(:error) allow(PersonalInformationLog).to receive(:create) end it 'logs the error, creates a PersonalInformationLog, and raises the error' do expect(Rails.logger).to receive(:error).with("Failed to generate PDF: #{error_message}") expect(PersonalInformationLog).to receive(:create).with( data: { form: claim.parsed_form, file_name: claim.guid }, error_class: '1010CGPdfGenerationError' ) expect { claim.to_pdf }.to raise_error(StandardError, error_message) end end end describe '#process_attachments!' do it 'raises a NotImplementedError' do expect { subject.process_attachments! }.to raise_error(NotImplementedError) end end describe '#regional_office' do it 'returns empty array' do expect(subject.regional_office).to eq([]) end end describe '#form_subjects' do it 'does not consider signAsRepresentative a form_subject' do claim_1 = described_class.new(form: { veteran: {}, signAsRepresentative: true }.to_json) expect(claim_1.form_subjects).to eq(%w[veteran]) end it 'returns a list of subjects present in #parsed_form' do claim_1 = described_class.new(form: { veteran: {} }.to_json) expect(claim_1.form_subjects).to eq(%w[veteran]) claim_2 = described_class.new(form: { veteran: {}, primaryCaregiver: {} }.to_json) expect(claim_2.form_subjects).to eq(%w[veteran primaryCaregiver]) claim_3 = described_class.new(form: { veteran: {}, secondaryCaregiverOne: {} }.to_json) expect(claim_3.form_subjects).to eq(%w[veteran secondaryCaregiverOne]) claim_4 = described_class.new(form: { veteran: {}, primaryCaregiver: {}, secondaryCaregiverOne: {} }.to_json) expect(claim_4.form_subjects).to eq(%w[veteran primaryCaregiver secondaryCaregiverOne]) claim_5 = described_class.new(form: { veteran: {}, primaryCaregiver: {}, secondaryCaregiverOne: {}, secondaryCaregiverTwo: {} }.to_json) expect(claim_5.form_subjects).to eq(%w[veteran primaryCaregiver secondaryCaregiverOne secondaryCaregiverTwo]) end context 'when no subjects are present' do it 'returns a an empty array' do expect(subject.form_subjects).to eq([]) end end end describe '#veteran_data' do it 'returns the veteran\'s data from the form as a hash' do subjects_data = { 'myName' => 'Veteran' } subject = described_class.new( form: { 'veteran' => subjects_data }.to_json ) expect(subject.veteran_data).to eq(subjects_data) end context 'when no data present' do it 'returns nil' do expect(subject.veteran_data).to be_nil end end end describe '#primary_caregiver_data' do it 'returns the veteran\'s data from the form as a hash' do subjects_data = { 'myName' => 'Primary Caregiver' } subject = described_class.new( form: { 'primaryCaregiver' => subjects_data }.to_json ) expect(subject.primary_caregiver_data).to eq(subjects_data) end context 'when no data present' do it 'returns nil' do expect(subject.primary_caregiver_data).to be_nil end end end describe '#secondary_caregiver_one_data' do it 'returns the veteran\'s data from the form as a hash' do subjects_data = { 'myName' => 'Secondary Caregiver I' } subject = described_class.new( form: { 'secondaryCaregiverOne' => subjects_data }.to_json ) expect(subject.secondary_caregiver_one_data).to eq(subjects_data) end context 'when no data present' do it 'returns nil' do expect(subject.secondary_caregiver_one_data).to be_nil end end end describe '#destroy_attachment' do let(:claim) { create(:caregivers_assistance_claim) } let(:attachment) { create(:form1010cg_attachment, :with_attachment) } context 'when attachment id is not present' do it 'does nothing' do claim.destroy! end end context 'when attachment exists' do before do claim.parsed_form['poaAttachmentId'] = attachment.guid end it 'destroys the attachment' do file = double expect_any_instance_of(Form1010cg::Attachment).to receive(:get_file).and_return(file) expect(file).to receive(:delete) claim.destroy! expect(Form1010cg::Attachment.exists?(id: attachment.id)).to be(false) end end context 'when the attachment doesnt exist' do before do claim.parsed_form['poaAttachmentId'] = SecureRandom.uuid end it 'does nothing' do claim.destroy! end end end describe '#secondary_caregiver_two_data' do it 'returns the veteran\'s data from the form as a hash' do subjects_data = { 'myName' => 'Secondary Caregiver II' } subject = described_class.new( form: { 'secondaryCaregiverTwo' => subjects_data }.to_json ) expect(subject.secondary_caregiver_two_data).to eq(subjects_data) end context 'when no data present' do it 'returns nil' do expect(subject.secondary_caregiver_two_data).to be_nil end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/higher_level_review_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::HigherLevelReview, type: :model do let(:guid) { SecureRandom.uuid } let(:form_data) do { stuff: 'things' } end let!(:appeal_submission) { create(:appeal_submission, type_of_appeal: 'SC', submitted_appeal_uuid: guid) } describe 'AppealSubmission association' do let!(:saved_claim_hlr) { described_class.create!(guid:, form: form_data.to_json) } it 'has one AppealSubmission' do expect(saved_claim_hlr.appeal_submission).to eq appeal_submission end it 'can be accessed from the AppealSubmission' do expect(appeal_submission.saved_claim_hlr).to eq saved_claim_hlr end end describe 'validation' do let!(:saved_claim_hlr) { described_class.new(guid:, form: form_data.to_json) } context 'no validation errors' do it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return([]) expect(saved_claim_hlr.validate).to be true end end context 'with validation errors' do let(:validation_errors) { ['error', 'error 2'] } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return(validation_errors) expect(Rails.logger).to receive(:warn).with('SavedClaim: schema validation errors detected for form 20-0996', guid:, count: 2) expect(saved_claim_hlr.validate).to be true end end context 'with JSON validator exception' do let(:exception) { JSON::Schema::ReadFailed.new('location', 'type') } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_raise(exception) expect(Rails.logger).to receive(:warn).with('SavedClaim: form_matches_schema error raised for form 20-0996', guid:, error: exception.message) expect(saved_claim_hlr.validate).to be true end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/education_benefits_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::EducationBenefits do describe '.form_class' do it 'raises an error if the form_type is invalid' do expect { described_class.form_class('foo') }.to raise_error('Invalid form type') end it 'returns the form class for a form type' do expect(described_class.form_class('1990')).to eq(SavedClaim::EducationBenefits::VA1990) end end it 'has #after_submit defined' do # have to stub this const because of the SavedClaim after_initialize callback stub_const("#{described_class}::FORM", 'SOME_FORM_NAME') expect(described_class.new).to respond_to(:after_submit) end describe '#in_progress_form_id' do it 'returns form_id' do form = create(:va1990) expect(form.in_progress_form_id).to eq(form.form_id) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/supplemental_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::SupplementalClaim, type: :model do let(:guid) { SecureRandom.uuid } let(:form_data) do { stuff: 'things' } end let!(:appeal_submission) { create(:appeal_submission, type_of_appeal: 'SC', submitted_appeal_uuid: guid) } describe 'AppealSubmission association' do let!(:saved_claim_sc) { described_class.create!(guid:, form: form_data.to_json) } it 'has one AppealSubmission' do expect(saved_claim_sc.appeal_submission).to eq appeal_submission end it 'can be accessed from the AppealSubmission' do expect(appeal_submission.saved_claim_sc).to eq saved_claim_sc end end describe 'validation' do let!(:saved_claim) { described_class.new(guid:, form: form_data.to_json) } before do allow(Rails.logger).to receive(:warn) end context 'no validation errors' do it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return([]) expect(saved_claim.validate).to be true end end context 'with validation errors' do let(:validation_errors) { ['error', 'error 2'] } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_return(validation_errors) expect(Rails.logger).to receive(:warn).with('SavedClaim: schema validation errors detected for form 20-0995', guid:, count: 2) expect(saved_claim.validate).to be true end end context 'with JSON validator exception' do let(:exception) { JSON::Schema::ReadFailed.new('location', 'type') } it 'returns true' do allow(JSON::Validator).to receive(:fully_validate).and_raise(exception) expect(Rails.logger).to receive(:warn).with('SavedClaim: form_matches_schema error raised for form 20-0995', guid:, error: exception.message) expect(saved_claim.validate).to be true end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/coe_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lgy/service' RSpec.describe SavedClaim::CoeClaim do describe '#send_to_lgy(edipi:, icn:)' do it 'logs an error to sentry if edipi is nil' do coe_claim = create(:coe_claim) allow(coe_claim).to receive(:prepare_form_data).and_return({}) allow_any_instance_of(LGY::Service).to receive(:put_application).and_return({}) expect(Rails.logger).to receive(:error).with(/COE application cannot be submitted without an edipi!/) coe_claim.send_to_lgy(edipi: nil, icn: nil) end it 'logs an error to sentry if edipi is an empty string' do coe_claim = create(:coe_claim) allow(coe_claim).to receive(:prepare_form_data).and_return({}) allow_any_instance_of(LGY::Service).to receive(:put_application).and_return({}) expect(Rails.logger).to receive(:error).with(/COE application cannot be submitted without an edipi!/) coe_claim.send_to_lgy(edipi: '', icn: nil) end it 'sends the right data to LGY' do # rubocop:disable Layout/LineLength coe_claim = create(:coe_claim, form: '{"relevantPriorLoans":[{"dateRange":{"from":"2017-01-01T00:00:00.000Z","to":""},"propertyAddress":{"propertyAddress1":"234","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":false,"vaLoanNumber":"123123123123","intent":"IRRRL"},{"dateRange":{"from":"2010-01-01T00:00:00.000Z","to":"2011-01-01T00:00:00.000Z"},"propertyAddress":{"propertyAddress1":"939393","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":true,"vaLoanNumber":"123123123123","intent":"REFI"}],"vaLoanIndicator":true,"periodsOfService":[{"serviceBranch":"Air Force","dateRange":{"from":"2000-01-01T00:00:00.000Z","to":"2010-01-16T00:00:00.000Z"}}],"identity":"ADSM","contactPhone":"2223334444","contactEmail":"vet@example.com","fullName":{"first":"Eddie","middle":"Joseph","last":"Caldwell"},"dateOfBirth":"1933-10-27","applicantAddress":{"country":"USA","street":"123 ANY ST","city":"ANYTOWN","state":"AL","postalCode":"54321"},"privacyAgreementAccepted":true}') # rubocop:enable Layout/LineLength expected_prepared_form_data = { 'status' => 'SUBMITTED', 'veteran' => { 'firstName' => 'Eddie', 'middleName' => 'Joseph', 'lastName' => 'Caldwell', 'suffixName' => '', 'dateOfBirth' => '1933-10-27', 'vetAddress1' => '123 ANY ST', 'vetAddress2' => '', 'vetCity' => 'ANYTOWN', 'vetState' => 'AL', 'vetZip' => '54321', 'vetZipSuffix' => nil, 'mailingAddress1' => '123 ANY ST', 'mailingAddress2' => '', 'mailingCity' => 'ANYTOWN', 'mailingState' => 'AL', 'mailingZip' => '54321', 'mailingZipSuffix' => '', 'contactPhone' => '2223334444', 'contactEmail' => 'vet@example.com', 'vaLoanIndicator' => true, 'vaHomeOwnIndicator' => true, 'activeDutyIndicator' => true, 'disabilityIndicator' => false }, 'relevantPriorLoans' => [{ 'vaLoanNumber' => '123123123123', 'startDate' => '2017-01-01T00:00:00.000Z', 'paidOffDate' => '', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => false, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => true, 'cashoutRefinaceRequested' => false, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '234', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }, { 'vaLoanNumber' => '123123123123', 'startDate' => '2010-01-01T00:00:00.000Z', 'paidOffDate' => '2011-01-01T00:00:00.000Z', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => true, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => false, 'cashoutRefinaceRequested' => true, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '939393', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }], 'periodsOfService' => [{ 'enteredOnDuty' => '2000-01-01T00:00:00.000Z', 'releasedActiveDuty' => '2010-01-16T00:00:00.000Z', 'militaryBranch' => 'AIR_FORCE', 'serviceType' => 'ACTIVE_DUTY', 'disabilityIndicator' => false }] } expect_any_instance_of(LGY::Service) .to receive(:put_application) .with(payload: expected_prepared_form_data) .and_return({}) coe_claim.send_to_lgy(edipi: '1222333222', icn: '1112227772V019333') end context 'send AIR_FORCE as branch for Air National Guard to LGY' do it 'sends the right data to LGY' do # rubocop:disable Layout/LineLength coe_claim = create(:coe_claim, form: '{"relevantPriorLoans":[{"dateRange":{"from":"2017-01-01T00:00:00.000Z","to":""},"propertyAddress":{"propertyAddress1":"234","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":false,"vaLoanNumber":"123123123123", "intent":"IRRRL"},{"dateRange":{"from":"2010-01-01T00:00:00.000Z","to":"2011-01-01T00:00:00.000Z"},"propertyAddress":{"propertyAddress1":"939393","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":true,"vaLoanNumber":"123123123123", "intent":"REFI"}],"vaLoanIndicator":true,"periodsOfService":[{"serviceBranch":"Air National Guard","dateRange":{"from":"2000-01-01T00:00:00.000Z","to":"2010-01-16T00:00:00.000Z"}}],"identity":"ADSM","contactPhone":"2223334444","contactEmail":"vet@example.com","fullName":{"first":"Eddie","middle":"Joseph","last":"Caldwell"},"dateOfBirth":"1933-10-27","applicantAddress":{"country":"USA","street":"123 ANY ST","city":"ANYTOWN","state":"AL","postalCode":"54321"},"privacyAgreementAccepted":true}') # rubocop:enable Layout/LineLength expected_prepared_form_data = { 'status' => 'SUBMITTED', 'veteran' => { 'firstName' => 'Eddie', 'middleName' => 'Joseph', 'lastName' => 'Caldwell', 'suffixName' => '', 'dateOfBirth' => '1933-10-27', 'vetAddress1' => '123 ANY ST', 'vetAddress2' => '', 'vetCity' => 'ANYTOWN', 'vetState' => 'AL', 'vetZip' => '54321', 'vetZipSuffix' => nil, 'mailingAddress1' => '123 ANY ST', 'mailingAddress2' => '', 'mailingCity' => 'ANYTOWN', 'mailingState' => 'AL', 'mailingZip' => '54321', 'mailingZipSuffix' => '', 'contactPhone' => '2223334444', 'contactEmail' => 'vet@example.com', 'vaLoanIndicator' => true, 'vaHomeOwnIndicator' => true, 'activeDutyIndicator' => true, 'disabilityIndicator' => false }, 'relevantPriorLoans' => [{ 'vaLoanNumber' => '123123123123', 'startDate' => '2017-01-01T00:00:00.000Z', 'paidOffDate' => '', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => false, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => true, 'cashoutRefinaceRequested' => false, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '234', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }, { 'vaLoanNumber' => '123123123123', 'startDate' => '2010-01-01T00:00:00.000Z', 'paidOffDate' => '2011-01-01T00:00:00.000Z', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => true, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => false, 'cashoutRefinaceRequested' => true, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '939393', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }], 'periodsOfService' => [{ 'enteredOnDuty' => '2000-01-01T00:00:00.000Z', 'releasedActiveDuty' => '2010-01-16T00:00:00.000Z', 'militaryBranch' => 'AIR_FORCE', 'serviceType' => 'RESERVE_NATIONAL_GUARD', 'disabilityIndicator' => false }] } expect_any_instance_of(LGY::Service) .to receive(:put_application) .with(payload: expected_prepared_form_data) .and_return({}) coe_claim.send_to_lgy(edipi: '1222333222', icn: '1112227772V019333') end end context 'send MARINES as branch for Marine Corps Reserve to LGY' do it 'sends the right data to LGY' do # rubocop:disable Layout/LineLength coe_claim = create(:coe_claim, form: '{"relevantPriorLoans":[{"dateRange":{"from":"2017-01-01T00:00:00.000Z","to":""},"propertyAddress":{"propertyAddress1":"234","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":false,"vaLoanNumber":"123123123123","intent":"IRRRL"},{"dateRange":{"from":"2010-01-01T00:00:00.000Z","to":"2011-01-01T00:00:00.000Z"},"propertyAddress":{"propertyAddress1":"939393","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":true,"vaLoanNumber":"123123123123","intent":"REFI"}],"vaLoanIndicator":true,"periodsOfService":[{"serviceBranch":"Marine Corps Reserve","dateRange":{"from":"2000-01-01T00:00:00.000Z","to":"2010-01-16T00:00:00.000Z"}}],"identity":"ADSM","contactPhone":"2223334444","contactEmail":"vet@example.com","fullName":{"first":"Eddie","middle":"Joseph","last":"Caldwell"},"dateOfBirth":"1933-10-27","applicantAddress":{"country":"USA","street":"123 ANY ST","city":"ANYTOWN","state":"AL","postalCode":"54321"},"privacyAgreementAccepted":true}') # rubocop:enable Layout/LineLength expected_prepared_form_data = { 'status' => 'SUBMITTED', 'veteran' => { 'firstName' => 'Eddie', 'middleName' => 'Joseph', 'lastName' => 'Caldwell', 'suffixName' => '', 'dateOfBirth' => '1933-10-27', 'vetAddress1' => '123 ANY ST', 'vetAddress2' => '', 'vetCity' => 'ANYTOWN', 'vetState' => 'AL', 'vetZip' => '54321', 'vetZipSuffix' => nil, 'mailingAddress1' => '123 ANY ST', 'mailingAddress2' => '', 'mailingCity' => 'ANYTOWN', 'mailingState' => 'AL', 'mailingZip' => '54321', 'mailingZipSuffix' => '', 'contactPhone' => '2223334444', 'contactEmail' => 'vet@example.com', 'vaLoanIndicator' => true, 'vaHomeOwnIndicator' => true, 'activeDutyIndicator' => true, 'disabilityIndicator' => false }, 'relevantPriorLoans' => [{ 'vaLoanNumber' => '123123123123', 'startDate' => '2017-01-01T00:00:00.000Z', 'paidOffDate' => '', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => false, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => true, 'cashoutRefinaceRequested' => false, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '234', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }, { 'vaLoanNumber' => '123123123123', 'startDate' => '2010-01-01T00:00:00.000Z', 'paidOffDate' => '2011-01-01T00:00:00.000Z', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => true, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => false, 'cashoutRefinaceRequested' => true, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '939393', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }], 'periodsOfService' => [{ 'enteredOnDuty' => '2000-01-01T00:00:00.000Z', 'releasedActiveDuty' => '2010-01-16T00:00:00.000Z', 'militaryBranch' => 'MARINES', 'serviceType' => 'RESERVE_NATIONAL_GUARD', 'disabilityIndicator' => false }] } expect_any_instance_of(LGY::Service) .to receive(:put_application) .with(payload: expected_prepared_form_data) .and_return({}) coe_claim.send_to_lgy(edipi: '1222333222', icn: '1112227772V019333') end end context 'send MARINES as branch for Marine Corps to LGY' do it 'sends the right data to LGY' do # rubocop:disable Layout/LineLength coe_claim = create(:coe_claim, form: '{"relevantPriorLoans":[{"dateRange":{"from":"2017-01-01T00:00:00.000Z","to":""},"propertyAddress":{"propertyAddress1":"234","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":false,"vaLoanNumber":"123123123123","intent":"IRRRL"},{"dateRange":{"from":"2010-01-01T00:00:00.000Z","to":"2011-01-01T00:00:00.000Z"},"propertyAddress":{"propertyAddress1":"939393","propertyAddress2":"234","propertyCity":"asdf","propertyState":"AL","propertyZip":"11111"},"propertyOwned":true,"vaLoanNumber":"123123123123","intent":"REFI"}],"vaLoanIndicator":true,"periodsOfService":[{"serviceBranch":"Marine Corps","dateRange":{"from":"2000-01-01T00:00:00.000Z","to":"2010-01-16T00:00:00.000Z"}}],"identity":"ADSM","contactPhone":"2223334444","contactEmail":"vet@example.com","fullName":{"first":"Eddie","middle":"Joseph","last":"Caldwell"},"dateOfBirth":"1933-10-27","applicantAddress":{"country":"USA","street":"123 ANY ST","city":"ANYTOWN","state":"AL","postalCode":"54321"},"privacyAgreementAccepted":true}') # rubocop:enable Layout/LineLength expected_prepared_form_data = { 'status' => 'SUBMITTED', 'veteran' => { 'firstName' => 'Eddie', 'middleName' => 'Joseph', 'lastName' => 'Caldwell', 'suffixName' => '', 'dateOfBirth' => '1933-10-27', 'vetAddress1' => '123 ANY ST', 'vetAddress2' => '', 'vetCity' => 'ANYTOWN', 'vetState' => 'AL', 'vetZip' => '54321', 'vetZipSuffix' => nil, 'mailingAddress1' => '123 ANY ST', 'mailingAddress2' => '', 'mailingCity' => 'ANYTOWN', 'mailingState' => 'AL', 'mailingZip' => '54321', 'mailingZipSuffix' => '', 'contactPhone' => '2223334444', 'contactEmail' => 'vet@example.com', 'vaLoanIndicator' => true, 'vaHomeOwnIndicator' => true, 'activeDutyIndicator' => true, 'disabilityIndicator' => false }, 'relevantPriorLoans' => [{ 'vaLoanNumber' => '123123123123', 'startDate' => '2017-01-01T00:00:00.000Z', 'paidOffDate' => '', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => false, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => true, 'cashoutRefinaceRequested' => false, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '234', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }, { 'vaLoanNumber' => '123123123123', 'startDate' => '2010-01-01T00:00:00.000Z', 'paidOffDate' => '2011-01-01T00:00:00.000Z', 'loanAmount' => nil, 'loanEntitlementCharged' => nil, 'propertyOwned' => true, 'oneTimeRestorationRequested' => false, 'irrrlRequested' => false, 'cashoutRefinaceRequested' => true, 'noRestorationEntitlementIndicator' => false, 'homeSellIndicator' => nil, 'propertyAddress1' => '939393', 'propertyAddress2' => '234', 'propertyCity' => 'asdf', 'propertyState' => 'AL', 'propertyCounty' => '', 'propertyZip' => '11111', 'propertyZipSuffix' => '' }], 'periodsOfService' => [{ 'enteredOnDuty' => '2000-01-01T00:00:00.000Z', 'releasedActiveDuty' => '2010-01-16T00:00:00.000Z', 'militaryBranch' => 'MARINES', 'serviceType' => 'ACTIVE_DUTY', 'disabilityIndicator' => false }] } expect_any_instance_of(LGY::Service) .to receive(:put_application) .with(payload: expected_prepared_form_data) .and_return({}) coe_claim.send_to_lgy(edipi: '1222333222', icn: '1112227772V019333') end end context 'no loan information' do it 'sends the right data to LGY' do # rubocop:disable Layout/LineLength coe_claim = create(:coe_claim, form: '{"intent":"REFI","vaLoanIndicator":true,"periodsOfService":[{"serviceBranch":"Air Force","dateRange":{"from":"2000-01-01T00:00:00.000Z","to":"2010-01-16T00:00:00.000Z"}}],"identity":"ADSM","contactPhone":"2223334444","contactEmail":"vet@example.com","fullName":{"first":"Eddie","middle":"Joseph","last":"Caldwell"},"dateOfBirth":"1933-10-27","applicantAddress":{"country":"USA","street":"123 ANY ST","city":"ANYTOWN","state":"AL","postalCode":"54321"},"privacyAgreementAccepted":true}') # rubocop:enable Layout/LineLength expected_prepared_form_data = { 'status' => 'SUBMITTED', 'veteran' => { 'firstName' => 'Eddie', 'middleName' => 'Joseph', 'lastName' => 'Caldwell', 'suffixName' => '', 'dateOfBirth' => '1933-10-27', 'vetAddress1' => '123 ANY ST', 'vetAddress2' => '', 'vetCity' => 'ANYTOWN', 'vetState' => 'AL', 'vetZip' => '54321', 'vetZipSuffix' => nil, 'mailingAddress1' => '123 ANY ST', 'mailingAddress2' => '', 'mailingCity' => 'ANYTOWN', 'mailingState' => 'AL', 'mailingZip' => '54321', 'mailingZipSuffix' => '', 'contactPhone' => '2223334444', 'contactEmail' => 'vet@example.com', 'vaLoanIndicator' => true, 'vaHomeOwnIndicator' => false, 'activeDutyIndicator' => true, 'disabilityIndicator' => false }, 'relevantPriorLoans' => [], 'periodsOfService' => [{ 'enteredOnDuty' => '2000-01-01T00:00:00.000Z', 'releasedActiveDuty' => '2010-01-16T00:00:00.000Z', 'militaryBranch' => 'AIR_FORCE', 'serviceType' => 'ACTIVE_DUTY', 'disabilityIndicator' => false }] } expect_any_instance_of(LGY::Service) .to receive(:put_application) .with(payload: expected_prepared_form_data) .and_return({}) coe_claim.send_to_lgy(edipi: '1222333222', icn: '1112227772V019333') end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/dependency_verification_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::DependencyVerificationClaim do let(:claim) { create(:dependency_verification_claim) } let(:user_object) { create(:evss_user, :loa3) } describe '#regional_office' do it 'returns an empty array for regional office' do expect(claim.regional_office).to eq([]) end end describe '#send_to_central_mail!' do it 'sends claim to central mail for processing' do claim.send_to_central_mail! end it 'calls process_attachments! method' do expect(claim).to receive(:process_attachments!) claim.send_to_central_mail! end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/education_career_counseling_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::EducationCareerCounselingClaim do let(:claim) { create(:education_career_counseling_claim_no_vet_information) } let(:user_object) { create(:evss_user, :loa3) } describe '#regional_office' do it 'returns an empty array for regional office' do expect(claim.regional_office).to eq([]) end end describe '#send_to_benefits_intake!' do it 'formats data before sending to central mail or benefits intake' do allow(claim).to receive(:process_attachments!) expect(claim).to receive(:update).with(form: a_string_including('"veteranSocialSecurityNumber":"333224444"')) claim.send_to_benefits_intake! end it 'calls process_attachments! method' do expect(claim).to receive(:process_attachments!) claim.send_to_benefits_intake! end it 'calls Lighthouse::SubmitBenefitsIntakeClaim job' do expect_any_instance_of(Lighthouse::SubmitBenefitsIntakeClaim).to receive(:perform).with(claim.id) claim.send_to_benefits_intake! end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/form210779_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::Form210779, type: :model do let(:valid_form_data) { build(:va210779).form } let(:invalid_form_data) { build(:va210779_invalid).form } let(:claim) { described_class.new(form:) } let(:form) { valid_form_data } describe 'validations' do context 'with valid form data' do it 'validates successfully' do expect(claim).to be_valid end end context 'with invalid form data' do let(:form) { invalid_form_data } it 'fails validation' do expect(claim).to be_invalid end end end describe '#send_confirmation_email' do it 'does not send email (MVP does not include email)' do expect(VANotify::EmailJob).not_to receive(:perform_async) claim.send_confirmation_email end end describe '#business_line' do it 'returns CMP for compensation claims' do expect(claim.business_line).to eq('CMP') end end describe '#document_type' do it 'returns 222 for nursing home' do expect(claim.document_type).to eq(222) end end describe '#regional_office' do it 'returns empty array' do expect(claim.regional_office).to eq([]) end end describe '#process_attachments!' do it 'queues Lighthouse submission job without attachments' do expect(Lighthouse::SubmitBenefitsIntakeClaim).to receive(:perform_async).with(claim.id) claim.process_attachments! end end describe '#to_pdf' do let(:saved_claim) { create(:va210779) } let(:pdf_path) { 'tmp/pdfs/21-0779_test.pdf' } let(:stamped_pdf_path) { 'tmp/pdfs/21-0779_test_stamped.pdf' } before do allow(PdfFill::Filler).to receive(:fill_form).and_return(pdf_path) allow(PdfFill::Forms::Va210779).to receive(:stamp_signature).and_return(stamped_pdf_path) end it 'generates the PDF using PdfFill::Filler' do expect(PdfFill::Filler).to receive(:fill_form).with(saved_claim, nil, {}).and_return(pdf_path) saved_claim.to_pdf end it 'calls stamp_signature with the filled PDF and parsed form data' do expect(PdfFill::Forms::Va210779).to receive(:stamp_signature).with( pdf_path, saved_claim.parsed_form ).and_return(stamped_pdf_path) saved_claim.to_pdf end it 'returns the stamped PDF path' do result = saved_claim.to_pdf expect(result).to eq(stamped_pdf_path) end it 'passes through file_name and fill_options to PdfFill::Filler' do file_name = 'custom_name.pdf' fill_options = { flatten: true } expect(PdfFill::Filler).to receive(:fill_form).with( saved_claim, file_name, fill_options ).and_return(pdf_path) saved_claim.to_pdf(file_name, fill_options) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/saved_claim/form214192_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SavedClaim::Form214192, type: :model do let(:valid_form_data) { JSON.parse(Rails.root.join('spec', 'fixtures', 'form214192', 'valid_form.json').read) } let(:invalid_form_data) do JSON.parse(Rails.root.join('spec', 'fixtures', 'form214192', 'invalid_form.json').read) end let(:claim) { described_class.new(form: valid_form_data.to_json) } describe 'validations' do let(:claim) { described_class.new(form: form.to_json) } let(:form) { valid_form_data.dup } context 'with valid form data' do it 'validates successfully' do claim = described_class.new(form: valid_form_data.to_json) expect(claim).to be_valid end end context 'with invalid form data from fixture' do it 'fails validation for multiple reasons' do claim = described_class.new(form: invalid_form_data.to_json) expect(claim).not_to be_valid # Should fail because: # - middle name exceeds maxLength of 1 # - missing SSN or VA file number # - missing required employment fields end end context 'OpenAPI schema validation' do it 'rejects middle name longer than 1 character' do form['veteranInformation']['fullName']['middle'] = 'AB' expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 1') end it 'rejects first name longer than 12 characters' do form['veteranInformation']['fullName']['first'] = 'A' * 13 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 12') end it 'rejects last name longer than 18 characters' do form['veteranInformation']['fullName']['last'] = 'A' * 19 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 18') end it 'rejects invalid SSN format' do form['veteranInformation']['ssn'] = '12345' # Too short expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('pattern') end it 'rejects address street exceeding maxLength' do form['veteranInformation']['address']['street'] = 'A' * 31 # Max is 30 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 30') end it 'accepts veteran address street2 up to 30 characters' do form['veteranInformation']['address']['street2'] = 'A' * 30 expect(claim).to be_valid end it 'rejects veteran address street2 longer than 30 characters' do form['veteranInformation']['address']['street2'] = 'A' * 31 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 30') end it 'accepts employer address street2 up to 30 characters' do form['employmentInformation']['employerAddress']['street2'] = 'A' * 30 expect(claim).to be_valid end it 'rejects employer address street2 longer than 30 characters' do form['employmentInformation']['employerAddress']['street2'] = 'A' * 31 expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('string length') expect(claim.errors.full_messages.join).to include('is greater than: 30') end it 'requires country field in address' do form['veteranInformation']['address'].delete('country') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires veteran information' do form.delete('veteranInformation') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires employment information' do form.delete('employmentInformation') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires veteran full name' do form['veteranInformation'].delete('fullName') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires veteran date of birth' do form['veteranInformation'].delete('dateOfBirth') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires employer name' do form['employmentInformation'].delete('employerName') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires employer address' do form['employmentInformation'].delete('employerAddress') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires type of work performed' do form['employmentInformation'].delete('typeOfWorkPerformed') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end it 'requires beginning date of employment' do form['employmentInformation'].delete('beginningDateOfEmployment') expect(claim).not_to be_valid expect(claim.errors.full_messages.join).to include('missing required properties') end end end describe '#send_confirmation_email' do it 'does not send email (MVP does not include email)' do expect(VANotify::EmailJob).not_to receive(:perform_async) claim.send_confirmation_email end end describe '#business_line' do it 'returns CMP for compensation claims' do expect(claim.business_line).to eq('CMP') end end describe '#document_type' do it 'returns 119 for employment information' do expect(claim.document_type).to eq(119) end end describe '#regional_office' do it 'returns empty array' do expect(claim.regional_office).to eq([]) end end describe '#process_attachments!' do it 'queues Lighthouse submission job without attachments' do expect(Lighthouse::SubmitBenefitsIntakeClaim).to receive(:perform_async).with(claim.id) claim.process_attachments! end end describe '#attachment_keys' do it 'returns empty array (no attachments in MVP)' do expect(claim.attachment_keys).to eq([]) end end describe '#to_pdf' do let(:pdf_path) { '/tmp/test_form.pdf' } let(:stamped_pdf_path) { '/tmp/test_form_stamped.pdf' } before do allow(PdfFill::Filler).to receive(:fill_form).and_return(pdf_path) allow(PdfFill::Forms::Va214192).to receive(:stamp_signature).and_return(stamped_pdf_path) end it 'generates PDF and stamps the signature' do result = claim.to_pdf expect(PdfFill::Filler).to have_received(:fill_form).with(claim, nil, {}) expect(PdfFill::Forms::Va214192).to have_received(:stamp_signature).with(pdf_path, claim.parsed_form) expect(result).to eq(stamped_pdf_path) end it 'passes fill_options to the filler' do fill_options = { extras_redesign: true } claim.to_pdf('test-id', fill_options) expect(PdfFill::Filler).to have_received(:fill_form).with(claim, 'test-id', fill_options) end end describe '#metadata_for_benefits_intake' do context 'with all fields present' do it 'returns correct metadata hash' do metadata = claim.metadata_for_benefits_intake expect(metadata).to eq( veteranFirstName: 'John', veteranLastName: 'Doe', fileNumber: '987654321', zipCode: '54321', businessLine: 'CMP' ) end end context 'when vaFileNumber is present' do it 'prefers vaFileNumber over ssn' do form_data = valid_form_data.dup form_data['veteranInformation']['vaFileNumber'] = '12345678' form_data['veteranInformation']['ssn'] = '999999999' claim_with_both = described_class.new(form: form_data.to_json) metadata = claim_with_both.metadata_for_benefits_intake expect(metadata[:fileNumber]).to eq('12345678') end end context 'when vaFileNumber is missing' do it 'falls back to ssn' do form_data = valid_form_data.dup form_data['veteranInformation'].delete('vaFileNumber') form_data['veteranInformation']['ssn'] = '111223333' claim_without_va_file = described_class.new(form: form_data.to_json) metadata = claim_without_va_file.metadata_for_benefits_intake expect(metadata[:fileNumber]).to eq('111223333') end end context 'when zipCode is missing' do it 'defaults to 00000 when employerAddress postalCode is missing' do form_data = valid_form_data.dup form_data['employmentInformation']['employerAddress'].delete('postalCode') claim_without_zip = described_class.new(form: form_data.to_json) metadata = claim_without_zip.metadata_for_benefits_intake expect(metadata[:zipCode]).to eq('00000') end it 'defaults to 00000 when employerAddress is missing' do form_data = valid_form_data.dup form_data['employmentInformation'].delete('employerAddress') claim_without_address = described_class.new(form: form_data.to_json) metadata = claim_without_address.metadata_for_benefits_intake expect(metadata[:zipCode]).to eq('00000') end end it 'always includes businessLine from business_line method' do metadata = claim.metadata_for_benefits_intake expect(metadata[:businessLine]).to eq('CMP') expect(metadata[:businessLine]).to eq(claim.business_line) end end describe 'FORM constant' do it 'is set to 21-4192' do expect(described_class::FORM).to eq('21-4192') end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/disability_compensation/form526_all_claim_bdd_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'disability_compensation/factories/api_provider_factory' RSpec.describe SavedClaim::DisabilityCompensation::Form526AllClaim do let(:user) { build(:disabilities_compensation_user) } before do create(:in_progress_form, form_id: FormProfiles::VA526ez::FORM_ID, user_uuid: user.uuid) Timecop.freeze(Date.new(2020, 8, 1)) end after { Timecop.return } describe '#to_submission_data' do context 'without a 4142 submission' do subject { described_class.from_hash(form_content) } let(:form_content) do JSON.parse(File.read('spec/support/disability_compensation_form/bdd_fe_submission.json')) end let(:submission_data) do JSON.parse(File.read('spec/support/disability_compensation_form/submissions/526_bdd.json')) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va1919_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA1919 do let(:instance) { build(:va1919) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-1919') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va8794_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA8794 do let(:instance) { build(:va8794) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-8794') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10297_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA10297 do let(:instance) { build(:va10297_simple_form) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10297') describe '#after_submit' do let(:user) { create(:user) } before do allow(VANotify::EmailJob).to receive(:perform_async) end describe 'confirmation email for 10297' do context 'when the form22_10297_confirmation_email feature flag is disabled' do it 'does not send a confirmation email' do allow(Flipper).to receive(:enabled?).with(:form22_10297_confirmation_email).and_return(false) subject = create(:va10297_simple_form) subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) end end context 'when the form22_10297_confirmation_email feature flag is enabled' do before do allow(Flipper).to receive(:enabled?).with(:form22_10297_confirmation_email).and_return(true) end context 'when the form10297_confirmation_email_with_silent_failure_processing feature flag is disabled' do before do allow(Flipper) .to receive(:enabled?) .with(:form10297_confirmation_email_with_silent_failure_processing) .and_return(false) end it 'sends an email without the silent failure callback parameters' do subject = create(:va10297_simple_form) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@test.com', 'form10297_confirmation_email_template_id', { 'first_name' => 'TEST', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end context 'when the form10297_confirmation_email_with_silent_failure_processing feature flag is enabled' do let(:callback_options) do { callback_metadata: { notification_type: 'confirmation', form_number: '22-10297', statsd_tags: { service: 'submit-10297-form', function: 'form_10297_failure_confirmation_email_sending' } } } end before { Flipper.enable(:form10297_confirmation_email_with_silent_failure_processing) } it 'sends an email with the silent failure callback parameters' do subject = create(:va10297_simple_form) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@test.com', 'form10297_confirmation_email_template_id', { 'first_name' => 'TEST', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" }, Settings.vanotify.services.va_gov.api_key, callback_options ) end end end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va5490_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA5490 do let(:instance) { build(:va5490) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-5490') describe '#after_submit' do let(:user) { create(:user) } describe 'sends confirmation email for the 5490' do it 'chapter 33' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va5490_chapter33) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'email@example.com', 'form5490_confirmation_email_template_id', { 'first_name' => 'MARK', 'benefit' => 'The Fry Scholarship (Chapter 33)', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end it 'chapter 35' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va5490) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'email@example.com', 'form5490_confirmation_email_template_id', { 'first_name' => 'MARK', 'benefit' => 'Survivors’ and Dependents’ Educational Assistance (DEA, Chapter 35)', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va1995_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA1995 do let(:instance) { build(:va1995) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-1995') describe '#after_submit' do let(:user) { create(:user) } before do allow(Flipper).to receive(:enabled?).and_call_original allow(Flipper).to receive(:enabled?).with(:form1995_confirmation_email).and_return(true) end describe 'sends confirmation email for the 1995' do it 'with benefit selected' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1995_full_form) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form1995_confirmation_email_template_id', { 'first_name' => 'FIRST', 'benefit' => 'Transfer of Entitlement Program (TOE)', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end it 'without benefit selected' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1995_full_form) parsed_form_data = JSON.parse(subject.form) parsed_form_data.delete('benefit') subject.form = parsed_form_data.to_json confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form1995_confirmation_email_template_id', { 'first_name' => 'FIRST', 'benefit' => '', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va0993_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA0993 do let(:instance) { build(:va0993) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-0993') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10203_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' require 'feature_flipper' RSpec.describe SavedClaim::EducationBenefits::VA10203 do let(:instance) { build(:va10203, education_benefits_claim: create(:education_benefits_claim)) } before do allow(Flipper).to receive(:enabled?).and_call_original end it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10203') describe '#in_progress_form_id' do it 'returns 22-10203' do expect(instance.in_progress_form_id).to eq('22-10203') end end describe '#after_submit' do context 'when the user is logged in' do let(:user) { create(:user) } let(:service) { instance_double(BenefitsEducation::Service) } before do allow(BenefitsEducation::Service).to receive(:new).and_return(service) allow(service).to receive(:get_gi_bill_status).and_return({}) end it 'calls get_gi_bill_status on the service' do instance.after_submit(user) expect(service).to have_received(:get_gi_bill_status) expect(BenefitsEducation::Service).to have_received(:new).with(user.icn).exactly(1).times end it 'sets the gi_bill_status instance variable' do # Load the VCR cassette response cassette_data = YAML.load_file('spec/support/vcr_cassettes/lighthouse/benefits_education/200_response_gt_6_mos.yml') # There are 2 interactions and the second one is the one we want response_body_string = cassette_data['http_interactions'][1]['response']['body']['string'] response_status = cassette_data['http_interactions'][1]['response']['status']['code'] # Parse the response JSON string to a hash parsed_body = JSON.parse(response_body_string) # Create a mock response object that matches what the service expects mock_raw_response = double('raw_response', status: response_status, body: parsed_body) mock_benefits_response = BenefitsEducation::Response.new(response_status, mock_raw_response) # Override the service mock for this specific test allow(service).to receive(:get_gi_bill_status).and_return(mock_benefits_response) instance.after_submit(user) expect(instance.instance_variable_get(:@gi_bill_status)).not_to be_nil end context 'when get_gi_bill_status raises an error' do before do allow(Rails.logger).to receive(:error) allow(service).to receive(:get_gi_bill_status).and_raise(StandardError) end it 'logs an error' do instance.after_submit(user) expect(Rails.logger).to have_received(:error) end end context 'stem automated decision processing' do it 'creates education_stem_automated_decision for user' do instance.after_submit(user) expect(instance.education_benefits_claim.education_stem_automated_decision).not_to be_nil expect(instance.education_benefits_claim.education_stem_automated_decision.user_uuid) .to eq(user.uuid) expect(instance.education_benefits_claim.education_stem_automated_decision.user_account_id) .to eq(user.user_account.id) expect(instance.education_benefits_claim.education_stem_automated_decision.auth_headers).not_to be_nil end it 'saves user auth_headers' do instance.after_submit(user) expect(instance.education_benefits_claim.education_stem_automated_decision.auth_headers).not_to be_nil end it 'always sets POA to nil' do instance.after_submit(user) expect(instance.education_benefits_claim.education_stem_automated_decision.poa).to be_nil end end context 'sending the confirmation email' do context 'when the form21_10203_confirmation_email feature flag is disabled' do before do Flipper.disable(:form21_10203_confirmation_email) expect(FeatureFlipper).to receive(:send_email?).once.and_return(false) end it 'does not call SendSchoolCertifyingOfficialsEmail' do expect { instance.after_submit(user) } .not_to change(EducationForm::SendSchoolCertifyingOfficialsEmail.jobs, :size) Flipper.enable(:form21_10203_confirmation_email) end end context 'when the form21_10203_confirmation_email feature flag is enabled' do before { Flipper.enable(:form21_10203_confirmation_email) } context 'when there is no form email' do it 'does not send a confirmation email' do Flipper.enable(:form21_10203_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = instance form = JSON.parse(subject.form) form.delete('email') subject.form = form.to_json subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) end end context 'when there is a form email' do context 'when the form1995_confirmation_email_with_silent_failure_processing feature flag is disabled' do before { Flipper.disable(:form1995_confirmation_email_with_silent_failure_processing) } it 'sends the confirmation email without the callback parameters' do allow(VANotify::EmailJob).to receive(:perform_async) instance.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form21_10203_confirmation_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => instance.education_benefits_claim.confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) Flipper.enable(:form21_10203_confirmation_email) end end context 'when the form1995_confirmation_email_with_silent_failure_processing feature flag is enabled' do let(:callback_options) do { callback_metadata: { notification_type: 'confirmation', form_number: '22-10203', statsd_tags: { service: 'submit-10203-form', function: 'form_10203_failure_confirmation_email_sending' } } } end before { Flipper.enable(:form1995_confirmation_email_with_silent_failure_processing) } it 'sends the confirmation email with the form email with the callback paarameters' do Flipper.enable(:form21_10203_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = instance subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form21_10203_confirmation_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => subject.education_benefits_claim.confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" }, Settings.vanotify.services.va_gov.api_key, callback_options ) end end end end end # we don't have to test the user because we're on the logged in path context 'sending the school certifying officials email' do context 'when the send_email? FeatureFlipper is false' do before { allow(FeatureFlipper).to receive(:send_email?).and_return(false) } it 'does not call SendSchoolCertifyingOfficialsEmail' do expect { instance.after_submit(user) } .not_to change(EducationForm::SendSchoolCertifyingOfficialsEmail.jobs, :size) end end context 'when the send_email? FeatureFlipper is true' do before { allow(FeatureFlipper).to receive(:send_email?).and_return(true) } context 'unauthorized' do before do allow(FeatureFlipper).to receive(:send_email?).and_return(true) expect(user).to receive(:authorize).with(:evss, :access?).and_return(false).at_least(:once) expect(user.authorize(:evss, :access?)).to be(false) mail = double('mail') allow(mail).to receive(:deliver_now) allow(StemApplicantConfirmationMailer).to receive(:build).with(instance, nil).and_return(mail) end it 'does not call SendSchoolCertifyingOfficialsEmail' do expect { instance.after_submit(user) } .not_to change(EducationForm::SendSchoolCertifyingOfficialsEmail.jobs, :size) end end context 'authorized' do before do expect(FeatureFlipper).to receive(:send_email?).once.and_return(true) expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once) expect(user.authorize(:evss, :access?)).to be(true) mail = double('mail') allow(mail).to receive(:deliver_now) allow(StemApplicantConfirmationMailer).to receive(:build).with(instance, nil).and_return(mail) Flipper.disable(:form21_10203_confirmation_email) end it 'increments the SendSchoolCertifyingOfficialsEmail job queue (calls the job)' do expect { instance.after_submit(user) } .to change(EducationForm::SendSchoolCertifyingOfficialsEmail.jobs, :size).by(1) end it 'calls SendSchoolCertifyingOfficialsEmail with correct arguments (gibill status is {})' do allow(EducationForm::SendSchoolCertifyingOfficialsEmail).to receive(:perform_async) instance.after_submit(user) expect(EducationForm::SendSchoolCertifyingOfficialsEmail) .to have_received(:perform_async) .with(instance.id, false, {}) end it 'calls SendSchoolCertifyingOfficialsEmail (remaining entitlement < 6 months)' do # Load the VCR cassette response cassette_data = YAML.load_file('spec/support/vcr_cassettes/lighthouse/benefits_education/200_response.yml') # There are 2 interactions and the second one is the one we want response_body_string = cassette_data['http_interactions'][1]['response']['body']['string'] response_status = cassette_data['http_interactions'][1]['response']['status']['code'] # Parse the response JSON string to a hash parsed_body = JSON.parse(response_body_string) # Create a mock response object that matches what the service expects mock_raw_response = double('raw_response', status: response_status, body: parsed_body) mock_benefits_response = BenefitsEducation::Response.new(response_status, mock_raw_response) # Override the service mock for this specific test allow(service).to receive(:get_gi_bill_status).and_return(mock_benefits_response) allow(EducationForm::SendSchoolCertifyingOfficialsEmail).to receive(:perform_async) instance.after_submit(user) expect(EducationForm::SendSchoolCertifyingOfficialsEmail) .to have_received(:perform_async) .with(instance.id, true, '11902614') end it 'calls SendSchoolCertifyingOfficialsEmail (remaining entitlement >= 6 months)' do # Load the VCR cassette response cassette_data = YAML.load_file('spec/support/vcr_cassettes/lighthouse/benefits_education/200_response_gt_6_mos.yml') # There are 2 interactions and the second one is the one we want response_body_string = cassette_data['http_interactions'][1]['response']['body']['string'] response_status = cassette_data['http_interactions'][1]['response']['status']['code'] # Parse the response JSON string to a hash parsed_body = JSON.parse(response_body_string) # Create a mock response object that matches what the service expects mock_raw_response = double('raw_response', status: response_status, body: parsed_body) mock_benefits_response = BenefitsEducation::Response.new(response_status, mock_raw_response) # Override the service mock for this specific test allow(service).to receive(:get_gi_bill_status).and_return(mock_benefits_response) allow(EducationForm::SendSchoolCertifyingOfficialsEmail).to receive(:perform_async) instance.after_submit(user) expect(EducationForm::SendSchoolCertifyingOfficialsEmail) .to have_received(:perform_async) .with(instance.id, false, '11902614') end end end end end context 'Not logged in' do before do mail = double('mail') allow(mail).to receive(:deliver_now) allow(StemApplicantConfirmationMailer).to receive(:build).with(instance, nil).and_return(mail) end it 'does not set @gi_bill_status' do instance.after_submit(nil) expect(instance.instance_variable_get(:@gi_bill_status)).to be_nil end it 'does not create education_stem_automated_decision' do instance.after_submit(nil) expect(instance.education_benefits_claim.education_stem_automated_decision).to be_nil end it 'does not call SendSchoolCertifyingOfficialsEmail' do expect { instance.after_submit(nil) } .not_to change(EducationForm::SendSchoolCertifyingOfficialsEmail.jobs, :size) end context 'when there is no form email' do it 'does not send a confirmation email' do Flipper.enable(:form21_10203_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = instance form = JSON.parse(subject.form) form.delete('email') subject.form = form.to_json subject.after_submit(nil) expect(VANotify::EmailJob).not_to have_received(:perform_async) end end context 'when there is a form email' do context 'when the form1995_confirmation_email_with_silent_failure_processing feature flag is disabled' do before { Flipper.disable(:form1995_confirmation_email_with_silent_failure_processing) } it 'sends the confirmation email without the callback parameters' do allow(VANotify::EmailJob).to receive(:perform_async) instance.after_submit(nil) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form21_10203_confirmation_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => instance.education_benefits_claim.confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) Flipper.enable(:form21_10203_confirmation_email) end end context 'when the form1995_confirmation_email_with_silent_failure_processing feature flag is enabled' do let(:callback_options) do { callback_metadata: { notification_type: 'confirmation', form_number: '22-10203', statsd_tags: { service: 'submit-10203-form', function: 'form_10203_failure_confirmation_email_sending' } } } end before { Flipper.enable(:form1995_confirmation_email_with_silent_failure_processing) } it 'sends the confirmation email with the form email with the callback paarameters' do Flipper.enable(:form21_10203_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = instance subject.after_submit(nil) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@sample.com', 'form21_10203_confirmation_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => subject.education_benefits_claim.confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" }, Settings.vanotify.services.va_gov.api_key, callback_options ) end end end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va0976_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA0976 do let(:instance) { build(:va0976) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-0976') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10275_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA10275 do let(:instance) { build(:va10275) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10275') describe '#after_submit' do let(:user) { create(:user) } describe 'confirmation email for 10275' do subject { create(:va10275) } it 'is skipped when feature flag is turned off' do allow(Flipper).to receive(:enabled?).with(:form22_10275_submission_email).and_return(false) allow(VANotify::EmailJob).to receive(:perform_async) subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) end it 'sends the email when feature flag is on' do allow(Flipper).to receive(:enabled?).with(:form22_10275_submission_email).and_return(true) allow(VANotify::EmailJob).to receive(:perform_async) subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'form_10275@example.com', 'form10275_submission_email_template_id', satisfy do |args| args[:submission_id] == subject.id && args[:agreement_type] == 'New commitment' && args[:institution_details].include?('Springfield University') && args[:institution_details].include?('US123456') && args[:additional_locations].include?('Springfield Technical Institute') && args[:additional_locations].include?('US654321') && args[:points_of_contact].include?('michael.brown@springfield.edu') && args[:points_of_contact].include?('emily.johnson@springfield.edu') && args[:submission_information].include?('Robert Smith') end, anything ) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10216_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA10216 do let(:instance) { build(:va10216) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10216') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va0803_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA0803 do let(:instance) { build(:va0803) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-0803') end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va1990_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA1990 do let(:instance) { build(:va1990) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-1990') describe '#after_submit' do let(:user) { create(:user) } describe 'confirmation email for the 1990' do it 'is sent to authenticated users' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1990_chapter33) subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async) end it 'is sent to unauthenticated users' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1990_chapter33) subject.after_submit(nil) expect(VANotify::EmailJob).to have_received(:perform_async) end it 'is skipped when feature flag is turned off' do Flipper.disable(:form1990_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1990_chapter33) subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) Flipper.enable(:form1990_confirmation_email) end it 'chapter 33' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1990_chapter33) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(nil) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'email@example.com', 'form1990_confirmation_email_template_id', { 'first_name' => 'MARK', 'benefit_relinquished' => '', 'benefits' => 'Post-9/11 GI Bill (Chapter 33)', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end it 'with relinquished' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va1990_with_relinquished) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(nil) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'email@example.com', 'form1990_confirmation_email_template_id', { 'first_name' => 'MARK', 'benefit_relinquished' => "__Benefits Relinquished:__\n^Montgomery GI Bill (MGIB-AD, Chapter 30)", 'benefits' => "Post-9/11 GI Bill (Chapter 33)\n\n^Montgomery GI Bill Selected Reserve " \ "(MGIB-SR or Chapter 1606) Educational Assistance Program\n\n^Post-Vietnam " \ 'Era Veterans’ Educational Assistance Program (VEAP or chapter 32)', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va5495_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA5495 do let(:instance) { build(:va5495) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-5495') describe '#after_submit' do let(:user) { create(:user) } it 'sends confirmation email for the 5495' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va5495_with_email) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'email@example.com', 'form5495_confirmation_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10282_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA10282 do let(:instance) { build(:va10282) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10282') describe '#after_submit' do subject { create(:va10282) } let(:user) { create(:user) } before do allow(VANotify::EmailJob).to receive(:perform_async) end context 'with the feature enabled' do before do allow(Flipper).to receive(:enabled?).with(:form22_10282_confirmation_email).and_return(true) end it 'queues an email job' do subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async) end end context 'with the feature disabled' do before do allow(Flipper).to receive(:enabled?).with(:form22_10282_confirmation_email).and_return(false) end it 'does nothing' do subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va0994_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA0994 do let(:instance) { build(:va0994_full_form) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-0994') describe '#after_submit' do let(:user) { create(:user) } describe 'confirmation email for 0994' do it 'is skipped when feature flag is turned off' do Flipper.disable(:form0994_confirmation_email) allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va0994_full_form) subject.after_submit(user) expect(VANotify::EmailJob).not_to have_received(:perform_async) Flipper.enable(:form0994_confirmation_email) end it 'sends v1 when they have applied for VA education benefits previously' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va0994_full_form) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@test.com', 'form0994_confirmation_email_template_id', { 'first_name' => 'TEST', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end it 'sends v2 when they have not applied for VA education benefits previously' do allow(VANotify::EmailJob).to receive(:perform_async) subject = create(:va0994_no_education_benefits) confirmation_number = subject.education_benefits_claim.confirmation_number subject.after_submit(user) expect(VANotify::EmailJob).to have_received(:perform_async).with( 'test@test.com', 'form0994_extra_action_confirmation_email_template_id', { 'first_name' => 'TEST', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => confirmation_number, 'regional_office_address' => "P.O. Box 4616\nBuffalo, NY 14240-4616" } ) end end end end
0
code_files/vets-api-private/spec/models/saved_claim
code_files/vets-api-private/spec/models/saved_claim/education_benefits/va10215_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lib/saved_claims_spec_helper' RSpec.describe SavedClaim::EducationBenefits::VA10215 do let(:instance) { build(:va10215) } it_behaves_like 'saved_claim' validate_inclusion(:form_id, '22-10215') end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/va_profile_redis/veteran_status_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_profile/models/veteran_status' require 'va_profile_redis/veteran_status' RSpec.describe VAProfileRedis::VeteranStatus, type: :model do subject { described_class.for_user(user) } let(:user) { build(:user, :loa3) } describe '.for_user' do it 'returns an instance of VeteranStatus with the user set' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.user).to eq(user) end end end describe '#title38_status' do context 'when user is loa3' do it 'returns title38_status value' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.title38_status).to be_present end end end context 'when user is not loa3' do let(:user) { build(:user, :loa1) } let(:edipi) { '1005127153' } before do allow(user).to receive(:edipi).and_return(edipi) end it 'returns nil' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.title38_status).to be_nil end end end end describe '#status' do context 'when user is loa3' do it 'returns status from the response' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.status).to be_present end end end context 'when user is not loa3' do let(:user) { build(:user, :loa1) } let(:edipi) { '1005127153' } before do allow(user).to receive(:edipi).and_return(edipi) end it 'returns not authorized' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[method]) do expect(subject.status).to eq(VAProfile::Response::RESPONSE_STATUS[:not_authorized]) end end end end describe '#response' do it 'returns a response either from redis or service' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.response).to be_present end end end describe 'private methods' do describe '#value_for' do it 'returns value for the given key from the veteran status response' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.send(:value_for, 'title38_status_code')).to be_present end end end describe '#response_from_redis_or_service' do context 'when cache is disabled' do before do allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(false) end it 'fetches response from the service' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body], allow_playback_repeats: true) do expect(subject.send(:response_from_redis_or_service)).to be_present end end end context 'when cache is enabled' do before do allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true) end it 'fetches response from cache or service' do VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body]) do expect(subject.send(:response_from_redis_or_service)).to be_present end end end end end end
0
code_files/vets-api-private/spec/models/va_profile_redis
code_files/vets-api-private/spec/models/va_profile_redis/v2/contact_information_spec.rb
# frozen_string_literal: true require 'rails_helper' describe VAProfileRedis::V2::ContactInformation do let(:user) { build(:user, :loa3) } let(:person_response) do raw_response = OpenStruct.new(status: 200, body: { 'bio' => person.to_hash }) VAProfile::ContactInformation::V2::PersonResponse.from(raw_response) end let(:contact_info) { VAProfileRedis::V2::ContactInformation.for_user(user) } let(:person) { build(:person, telephones:) } let(:telephones) do [ build(:telephone), build(:telephone, :home), build(:telephone, :work), build(:telephone, :temporary), build(:telephone, :fax) ] end before do allow(VAProfile::Models::Person).to receive(:build_from).and_return(person) end [404, 400].each do |status| context "with a #{status} from get_person" do let(:get_person_calls) { 'once' } before do allow(VAProfile::Configuration::SETTINGS.contact_information).to receive(:cache_enabled).and_return(true) service = double allow(VAProfile::ContactInformation::V2::Service).to receive(:new).with(user).and_return(service) expect(service).to receive(:get_person).public_send( get_person_calls ).and_return( VAProfile::ContactInformation::V2::PersonResponse.new(status, person: nil) ) end it 'caches the empty response' do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.email).to be_nil expect(contact_info.home_phone).to be_nil end end context 'when the cache is destroyed' do let(:get_person_calls) { 'twice' } it 'makes a new request' do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.email).to be_nil end VAProfileRedis::V2::Cache.invalidate(user) expect(VAProfileRedis::V2::ContactInformation.for_user(user).email).to be_nil end end end end describe '.new' do it 'creates an instance with user attributes' do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.user).to eq(user) end end end describe '#response' do context 'when the cache is empty' do it 'caches and return the response', :aggregate_failures do allow_any_instance_of( VAProfile::ContactInformation::V2::Service ).to receive(:get_person).and_return(person_response) VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do if VAProfile::Configuration::SETTINGS.contact_information.cache_enabled expect(contact_info.redis_namespace).to receive(:set).once end expect_any_instance_of(VAProfile::ContactInformation::V2::Service).to receive(:get_person).once expect(contact_info.status).to eq 200 expect(contact_info.response.person).to have_deep_attributes(person) end end end context 'when there is cached data' do it 'returns the cached data', :aggregate_failures do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do contact_info.cache(user.icn, person_response) expect_any_instance_of(VAProfile::ContactInformation::V2::Service).not_to receive(:get_person) expect(contact_info.response.person).to have_deep_attributes(person) end end end end describe 'contact information attributes' do context 'with a successful response' do before do allow(VAProfile::Models::Person).to receive(:build_from).and_return(person) allow_any_instance_of( VAProfile::ContactInformation::V2::Service ).to receive(:get_person).and_return(person_response) end describe '#email' do it 'returns the users email address object', :aggregate_failures do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.email).to eq person.emails.first expect(contact_info.email.class).to eq VAProfile::Models::Email end end end describe '#residential_address' do it 'returns the users residential address object', :aggregate_failures do residence = address_for VAProfile::Models::Address::RESIDENCE VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.residential_address).to eq residence expect(contact_info.residential_address.class).to eq VAProfile::Models::Address end end end describe '#mailing_address' do it 'returns the users mailing address object', :aggregate_failures do correspondence = address_for VAProfile::Models::Address::CORRESPONDENCE VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.mailing_address).to eq correspondence expect(contact_info.mailing_address.class).to eq VAProfile::Models::Address end end end describe '#home_phone' do it 'returns the users home phone object', :aggregate_failures do phone = phone_for VAProfile::Models::Telephone::HOME VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.home_phone).to eq phone expect(contact_info.home_phone.class).to eq VAProfile::Models::Telephone end end end describe '#mobile_phone' do it 'returns the users mobile phone object', :aggregate_failures do phone = phone_for VAProfile::Models::Telephone::MOBILE VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.mobile_phone).to eq phone expect(contact_info.mobile_phone.class).to eq VAProfile::Models::Telephone end end end describe '#work_phone' do it 'returns the users work phone object', :aggregate_failures do phone = phone_for VAProfile::Models::Telephone::WORK VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.work_phone).to eq phone expect(contact_info.work_phone.class).to eq VAProfile::Models::Telephone end end end describe '#temporary_phone' do it 'returns the users temporary phone object', :aggregate_failures do phone = phone_for VAProfile::Models::Telephone::TEMPORARY VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.temporary_phone).to eq phone expect(contact_info.temporary_phone.class).to eq VAProfile::Models::Telephone end end end describe '#fax_number' do it 'returns the users FAX object', :aggregate_failures do fax = phone_for VAProfile::Models::Telephone::FAX VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do expect(contact_info.fax_number).to eq fax expect(contact_info.fax_number.class).to eq VAProfile::Models::Telephone end end end end context 'with an error response' do before do allow_any_instance_of(VAProfile::ContactInformation::V2::Service).to receive(:get_person).and_raise( Common::Exceptions::BackendServiceException ) end describe '#email' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.email }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#residential_address' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.residential_address }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#mailing_address' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.mailing_address }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#home_phone' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.home_phone }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#mobile_phone' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.mobile_phone }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#work_phone' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.work_phone }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#temporary_phone' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.temporary_phone }.to raise_error( Common::Exceptions::BackendServiceException ) end end describe '#fax_number' do it 'raises a Common::Exceptions::BackendServiceException error' do expect { contact_info.fax_number }.to raise_error( Common::Exceptions::BackendServiceException ) end end end context 'with an empty respose body' do let(:empty_response) do raw_response = OpenStruct.new(status: 500, body: nil) VAProfile::ContactInformation::V2::PersonResponse.from(raw_response) end before do allow(VAProfile::Models::Person).to receive(:build_from).and_return(nil) allow_any_instance_of( VAProfile::ContactInformation::V2::Service ).to receive(:get_person).and_return(empty_response) end describe '#email' do it 'returns nil' do expect(contact_info.email).to be_nil end end describe '#residential_address' do it 'returns nil' do expect(contact_info.residential_address).to be_nil end end describe '#mailing_address' do it 'returns nil' do expect(contact_info.mailing_address).to be_nil end end describe '#home_phone' do it 'returns nil' do expect(contact_info.home_phone).to be_nil end end describe '#mobile_phone' do it 'returns nil' do expect(contact_info.mobile_phone).to be_nil end end describe '#work_phone' do it 'returns nil' do expect(contact_info.work_phone).to be_nil end end describe '#temporary_phone' do it 'returns nil' do expect(contact_info.temporary_phone).to be_nil end end describe '#fax_number' do it 'returns nil' do expect(contact_info.fax_number).to be_nil end end end end end def address_for(address_type) person.addresses.find { |address| address.address_pou == address_type } end def phone_for(phone_type) person.telephones.find { |telephone| telephone.phone_type == phone_type } end
0
code_files/vets-api-private/spec/models/va_profile_redis
code_files/vets-api-private/spec/models/va_profile_redis/v2/cache_spec.rb
# frozen_string_literal: true require 'rails_helper' describe VAProfileRedis::V2::Cache do let(:user) { build(:user, :loa3) } describe 'ContactInformationServiceV2' do before do allow(VAProfile::Configuration::SETTINGS.contact_information).to receive(:cache_enabled).and_return(true) end describe '.invalidate' do context 'when user.vet360_contact_info is present' do it 'invalidates the va-profile-contact-info-response cache' do VCR.use_cassette('va_profile/v2/contact_information/person', VCR::MATCH_EVERYTHING) do VAProfileRedis::V2::ContactInformation.for_user(user) end expect(VAProfileRedis::V2::ContactInformation.exists?(user.icn)).to be(true) VAProfileRedis::V2::Cache.invalidate(user) expect(VAProfileRedis::V2::ContactInformation.exists?(user.icn)).to be(false) end end context 'when user.vet360_contact_info is nil' do it 'does not call #destroy' do expect_any_instance_of(Common::RedisStore).not_to receive(:destroy) VAProfileRedis::V2::Cache.invalidate(user) end end end end end
0
code_files/vets-api-private/spec/models/mhv
code_files/vets-api-private/spec/models/mhv/mr/health_condition_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe MHV::MR::HealthCondition, type: :model do describe '.from_fhir' do context 'with a valid FHIR::Condition resource' do subject(:health_condition) { described_class.from_fhir(fhir_condition) } let(:location_resource) do FHIR::Location.new( id: 'loc-1', name: 'Test Facility' ) end let(:practitioner_resource) do FHIR::Practitioner.new( id: 'prov-1', name: [FHIR::HumanName.new(text: 'Dr. Test')] ) end let(:extension) do FHIR::Extension.new( url: 'http://hl7.org/fhir/StructureDefinition/alternate-reference', valueReference: FHIR::Reference.new(reference: '#loc-1') ) end let(:recorder_reference) do FHIR::Reference.new( reference: '#prov-1', extension: [extension] ) end let(:fhir_condition) do FHIR::Condition.new( id: '123', code: FHIR::CodeableConcept.new(text: 'Test Condition'), recordedDate: '2022-04-29', recorder: recorder_reference, contained: [location_resource, practitioner_resource], note: [ FHIR::Annotation.new(text: 'Note one'), FHIR::Annotation.new(text: 'Note two') ] ) end it 'maps id correctly' do expect(health_condition.id).to eq('123') end it 'maps name correctly' do expect(health_condition.name).to eq('Test Condition') end it 'maps date correctly' do expect(health_condition.date).to eq('2022-04-29') end it 'maps facility correctly' do expect(health_condition.facility).to eq('Test Facility') end it 'maps provider correctly' do expect(health_condition.provider).to eq('Dr. Test') end it 'maps comments correctly' do expect(health_condition.comments).to eq(['Note one', 'Note two']) end end context 'when given nil' do it 'returns nil' do expect(described_class.from_fhir(nil)).to be_nil end end context 'with missing fields and contained resources' do subject(:health_condition) { described_class.from_fhir(fhir_condition) } let(:fhir_condition) { FHIR::Condition.new(id: '456') } it 'sets id correctly' do expect(health_condition.id).to eq('456') end it 'defaults name to nil' do expect(health_condition.name).to be_nil end it 'defaults date to nil' do expect(health_condition.date).to be_nil end it 'defaults facility to nil' do expect(health_condition.facility).to be_nil end it 'defaults provider to nil' do expect(health_condition.provider).to be_nil end it 'defaults comments to an empty array' do expect(health_condition.comments).to eq([]) end end end end
0
code_files/vets-api-private/spec/models/mhv
code_files/vets-api-private/spec/models/mhv/mr/allergy_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe MHV::MR::Allergy, type: :model do describe '.from_fhir' do context 'with a valid FHIR::AllergyIntolerance resource' do subject(:allergy) { described_class.from_fhir(fhir_allergy) } let(:location_resource) do FHIR::Location.new( id: 'loc-1', name: 'Test Location' ) end let(:observed_ext) do FHIR::Extension.new( url: 'http://example.org/fhir/StructureDefinition/allergyObservedHistoric', valueCode: 'o' ) end let(:recorder_ext) do FHIR::Extension.new( url: 'http://hl7.org/fhir/StructureDefinition/alternate-reference', valueReference: FHIR::Reference.new(reference: '#loc-1') ) end let(:recorder_ref) do FHIR::Reference.new( reference: '#loc-1', extension: [recorder_ext], display: 'Dr. Allergy' ) end let(:fhir_allergy) do FHIR::AllergyIntolerance.new( id: 'a1', code: FHIR::CodeableConcept.new(text: 'Peanut Allergy'), recordedDate: '2021-05-10', category: %w[food environment], reaction: [ FHIR::AllergyIntolerance::Reaction.new( manifestation: [ FHIR::CodeableConcept.new(text: 'rash'), FHIR::CodeableConcept.new(text: 'anaphylaxis') ] ) ], extension: [observed_ext], note: [FHIR::Annotation.new(text: 'Carry epi pen')], recorder: recorder_ref, contained: [location_resource] ) end it 'maps id correctly' do expect(allergy.id).to eq('a1') end it 'maps name correctly' do expect(allergy.name).to eq('Peanut Allergy') end it 'maps date correctly' do expect(allergy.date).to eq('2021-05-10') end it 'maps categories correctly' do expect(allergy.categories).to eq(%w[food environment]) end it 'maps reactions correctly' do expect(allergy.reactions).to eq(%w[rash anaphylaxis]) end it 'maps location correctly' do expect(allergy.location).to eq('Test Location') end it 'maps observedHistoric correctly' do expect(allergy.observedHistoric).to eq('o') end it 'maps notes correctly' do expect(allergy.notes).to eq('Carry epi pen') end it 'maps provider correctly' do expect(allergy.provider).to eq('Dr. Allergy') end end context 'when given nil' do it 'returns nil' do expect(described_class.from_fhir(nil)).to be_nil end end context 'with missing fields and contained resources' do subject(:allergy) { described_class.from_fhir(fhir_allergy) } let(:fhir_allergy) { FHIR::AllergyIntolerance.new(id: 'b2') } it 'sets id correctly' do expect(allergy.id).to eq('b2') end it 'defaults name to nil' do expect(allergy.name).to be_nil end it 'defaults date to nil' do expect(allergy.date).to be_nil end it 'defaults categories to an empty array' do expect(allergy.categories).to eq([]) end it 'defaults reactions to an empty array' do expect(allergy.reactions).to eq([]) end it 'defaults location to nil' do expect(allergy.location).to be_nil end it 'defaults observedHistoric to nil' do expect(allergy.observedHistoric).to be_nil end it 'defaults notes to nil' do expect(allergy.notes).to be_nil end it 'defaults provider to nil' do expect(allergy.provider).to be_nil end end end end
0
code_files/vets-api-private/spec/models/mhv
code_files/vets-api-private/spec/models/mhv/mr/vaccine_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe MHV::MR::Vaccine do describe '.from_fhir' do context 'with a valid FHIR::Immunization resource' do subject(:vaccine) { described_class.from_fhir(immunization) } let(:location_resource) do FHIR::Location.new( id: 'in-location-2', name: 'Test Location' ) end let(:observation_resource) do FHIR::Observation.new( id: 'in-reaction-2', code: FHIR::CodeableConcept.new(text: 'FEVER') ) end let(:immunization) do FHIR::Immunization.new( id: '12345', vaccineCode: FHIR::CodeableConcept.new(text: 'TEST VACCINE'), occurrenceDateTime: '2023-10-27T10:00:00-04:00', location: FHIR::Reference.new(reference: '#in-location-2'), manufacturer: FHIR::Reference.new(display: 'Test Manufacturer'), reaction: [ FHIR::Immunization::Reaction.new( detail: FHIR::Reference.new(reference: '#in-reaction-2') ) ], note: [ FHIR::Annotation.new(text: 'Note 1'), FHIR::Annotation.new(text: 'Note 2') ], contained: [location_resource, observation_resource] ) end it 'maps id correctly' do expect(vaccine.id).to eq('12345') end it 'maps name correctly' do expect(vaccine.name).to eq('TEST VACCINE') end it 'maps date_received correctly' do expect(vaccine.date_received).to eq('2023-10-27T10:00:00-04:00') end it 'maps location correctly' do expect(vaccine.location).to eq('Test Location') end it 'maps manufacturer correctly' do expect(vaccine.manufacturer).to eq('Test Manufacturer') end it 'maps reactions correctly' do expect(vaccine.reactions).to eq('FEVER') end it 'maps notes correctly' do expect(vaccine.notes).to eq(['Note 1', 'Note 2']) end end context 'when given nil' do it 'returns nil' do expect(described_class.from_fhir(nil)).to be_nil end end context 'with missing contained resources and attributes' do subject(:vaccine) { described_class.from_fhir(immunization) } let(:immunization) { FHIR::Immunization.new(id: '1') } it 'sets id correctly' do expect(vaccine.id).to eq('1') end it 'defaults name to nil' do expect(vaccine.name).to be_nil end it 'defaults date_received to nil' do expect(vaccine.date_received).to be_nil end it 'defaults location to an empty string' do expect(vaccine.location).to be_nil end it 'defaults manufacturer to an empty string' do expect(vaccine.manufacturer).to be_nil end it 'defaults reactions to an empty string' do expect(vaccine.reactions).to be_nil end it 'defaults notes to an empty array' do expect(vaccine.notes).to eq([]) end end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/audit/log_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Audit::Log, type: :model do subject { build(:audit_log) } describe 'validations' do it { is_expected.to validate_presence_of(:subject_user_identifier) } it { is_expected.to validate_presence_of(:acting_user_identifier) } it { is_expected.to validate_presence_of(:event_id) } it { is_expected.to validate_presence_of(:event_description) } it { is_expected.to validate_presence_of(:event_status) } it { is_expected.to validate_presence_of(:event_occurred_at) } it { is_expected.to validate_presence_of(:message) } end describe 'enums' do let(:expected_values) do { icn: 'icn', logingov_uuid: 'logingov_uuid', idme_uuid: 'idme_uuid', mhv_id: 'mhv_id', dslogon_id: 'dslogon_id', system_hostname: 'system_hostname' } end it { expect(subject).to define_enum_for(:subject_user_identifier_type).with_values(expected_values) .with_prefix(true) .backed_by_column_of_type(:enum) } it { expect(subject).to define_enum_for(:acting_user_identifier_type).with_values(expected_values) .with_prefix(true) .backed_by_column_of_type(:enum) } end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents/child_stopped_attending_school_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependents::ChildStoppedAttendingSchool do let(:child_info) do { 'date_child_left_school' => '2019-03-03', 'ssn' => '213648794', 'birth_date' => '2003-03-03', 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }, 'dependent_income' => true } end let(:formatted_params_result) do { 'event_date' => '2019-03-03', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.', 'ssn' => '213648794', 'birth_date' => '2003-03-03', 'dependent_income' => 'Y' } end describe '#format_info' do it 'formats child stopped attending school params for submission' do formatted_info = described_class.new(child_info).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents/veteran_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependents::Veteran do let(:address) { { addrs_one_txt: '123 mainstreet', cntry_nm: 'USA', vnp_ptcpnt_addrs_id: '116343' } } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:veteran_response_result_sample) do { vnp_participant_id: '149500', type: 'veteran', benefit_claim_type_end_product: '134', vnp_participant_address_id: '116343', file_number: '1234' } end let(:user) { create(:evss_user, :loa3) } let(:vet) { described_class.new('12345', user) } let(:formatted_params_result) do { 'first' => 'WESLEY', 'last' => 'FORD', 'phone_number' => '1112223333', 'email_address' => 'foo@foo.com', 'country_name' => 'USA', 'address_line1' => '2037400 twenty ninth St', 'city' => 'Pasadena', 'state_code' => 'CA', 'zip_code' => '21122', 'vet_ind' => 'Y', 'martl_status_type_cd' => 'Separated' } end describe '#formatted_params' do it 'formats params given a veteran that is separated' do expect(vet.formatted_params(all_flows_payload)).to include(formatted_params_result) end it 'formats params given a veteran that is married' do formatted_params_result['martl_status_type_cd'] = 'Married' all_flows_payload['dependents_application']['does_live_with_spouse']['spouse_does_live_with_veteran'] = true expect(vet.formatted_params(all_flows_payload)).to include(formatted_params_result) end end describe '#veteran_response' do it 'formats params veteran response' do expect( vet.veteran_response( { vnp_ptcpnt_id: '149500' }, address, { va_file_number: '1234', claim_type_end_product: '134', location_id: '310', net_worth_over_limit_ind: 'Y' } ) ).to include(veteran_response_result_sample) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents/divorce_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependents::Divorce do let(:divorce_info) do { 'date' => '2020-01-01', 'ssn' => '848525794', 'birth_date' => '1990-03-03', 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }, 'location' => { 'state' => 'FL', 'city' => 'Tampa' }, 'reason_marriage_ended' => 'Divorce', 'spouse_income' => false } end let(:formatted_params_result) do { 'divorce_state' => 'FL', 'divorce_city' => 'Tampa', 'ssn' => '848525794', 'birth_date' => '1990-03-03', 'divorce_country' => nil, 'marriage_termination_type_code' => 'Divorce', 'end_date' => DateTime.parse("#{divorce_info['date']} 12:00:00").to_time.iso8601, 'vet_ind' => 'N', 'type' => 'divorce', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.', 'spouse_income' => 'N' } end describe '#format_info' do it 'formats divorce params for submission' do formatted_info = described_class.new(divorce_info).format_info expect(formatted_info).to eq(formatted_params_result) end end end
0
code_files/vets-api-private/spec/models
code_files/vets-api-private/spec/models/bgs_dependents/death_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGSDependents::Death do let(:death_info) do { 'date' => '2019-03-03', 'vet_ind' => 'N', 'ssn' => '846685794', 'birth_date' => '2009-03-03', 'location' => { 'state' => 'CA', 'city' => 'Hollywood' }, 'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }, 'dependent_type' => 'CHILD', 'child_status' => { 'child_under18' => true }, 'dependent_income' => false } end let(:formatted_params_result) do { 'death_date' => '2019-03-03T12:00:00+00:00', 'vet_ind' => 'N', 'ssn' => '846685794', 'birth_date' => '2009-03-03', 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.', 'dependent_income' => 'N' } end describe '#format_info' do it 'formats death params for submission' do formatted_info = described_class.new(death_info).format_info expect(formatted_info).to eq(formatted_params_result) end end describe '#format_info for spouse' do it 'formats death params for submission' do formatted_info = described_class.new(death_info.merge({ 'dependent_type' => 'SPOUSE' })).format_info expect(formatted_info).to eq(formatted_params_result.merge({ 'marriage_termination_type_code' => 'Death' })) end end end