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
|
code_files/vets-api-private/spec/mailers/stem_applicant_sco_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe StemApplicantScoMailer, type: [:mailer] do
subject do
described_class.build(education_benefits_claim.id, ga_client_id).deliver_now
end
let(:education_benefits_claim) { create(:va10203) }
let(:applicant) { education_benefits_claim.open_struct_form }
let(:ga_client_id) { '123456543' }
describe '#build' do
it 'includes subject' do
expect(subject.subject).to eq(StemApplicantScoMailer::SUBJECT)
end
it 'includes applicant email' do
expect(subject.to).to eq([applicant.email])
end
context 'applicant information in email body' do
it 'includes veteran first and last name' do
name = applicant.veteranFullName
first_initial_last_name = "#{name.first} #{name.last}"
expect(subject.body.raw_source).to include("Dear #{first_initial_last_name},")
end
it 'includes school name' do
expect(subject.body.raw_source).to include(
"We sent the email below to the School Certifying Official (SCO) at #{applicant.schoolName} to gather"
)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/mailers/direct_deposit_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DirectDepositMailer, feature: :direct_deposit,
team_owner: :vfs_authenticated_experience_backend, type: :mailer do
subject do
described_class.build(email, google_analytics_client_id).deliver_now
end
let(:dd_type) { :comp_pen }
let(:email) { 'foo@example.com' }
let(:google_analytics_client_id) { '123456543' }
describe '#build' do
it 'includes all info' do
expect(subject.subject).to eq('Confirmation - Your direct deposit information changed on VA.gov')
expect(subject.to).to eq(['foo@example.com'])
expect(subject.body.raw_source).to include(
"We're sending this email to confirm that you've recently changed your direct deposit " \
'information in your VA.gov account profile.'
)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/mailers/stem_applicant_denial_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe StemApplicantDenialMailer, type: [:mailer] do
subject do
described_class.build(education_benefits_claim, ga_client_id).deliver_now
end
let(:education_benefits_claim) do
claim = build(:education_benefits_claim_10203)
claim.save
claim
end
let(:applicant) { education_benefits_claim.saved_claim.open_struct_form }
let(:ga_client_id) { '123456543' }
describe '#build' do
it 'includes subject' do
expect(subject.subject).to eq(StemApplicantDenialMailer::SUBJECT)
end
it 'includes recipients' do
expect(subject.to).to eq([applicant.email])
end
context 'applicant information in email body' do
it 'includes date received' do
date_received = education_benefits_claim.saved_claim.created_at.strftime('%b %d, %Y')
expect(subject.body.raw_source).to include(date_received)
end
it 'includes claim status url' do
env = FeatureFlipper.staging_email? ? 'staging.' : ''
claim_status_url = "https://#{env}va.gov/track-claims/your-stem-claims/#{education_benefits_claim.id}/status"
expect(subject.body.raw_source).to include(claim_status_url)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/mailers/school_certifying_officials_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SchoolCertifyingOfficialsMailer, type: [:mailer] do
subject do
described_class.build(education_benefits_claim.id, recipients, ga_client_id).deliver_now
end
let(:education_benefits_claim) { create(:va10203) }
let(:applicant) { education_benefits_claim.open_struct_form }
let(:recipients) { ['foo@example.com'] }
let(:ga_client_id) { '123456543' }
describe '#build' do
it 'includes subject' do
expect(subject.subject).to eq(SchoolCertifyingOfficialsMailer::SUBJECT)
end
it 'includes recipients' do
expect(subject.to).to eq(recipients)
end
context 'applicant information in email body' do
it 'includes veteran full name' do
name = applicant.veteranFullName
first_initial_last_name = "#{name.first[0, 1]} #{name.last}"
expect(subject.body.raw_source).to include("Student's name: #{first_initial_last_name}")
end
it 'includes school email address' do
expect(subject.body.raw_source).to include("Student's school email address: #{applicant.schoolEmailAddress}")
end
it 'includes school student id' do
expect(subject.body.raw_source).to include("Student's school ID number: #{applicant.schoolStudentId}")
end
it 'includes updated text' do
expect(subject.body.raw_source).to include('this STEM program (specify semester or quarter')
expect(subject.body.raw_source).to include('and exclude in-progress credits):')
expect(subject.body.raw_source).to include('Total required credits for STEM degree program')
end
it 'includes the correct stem link' do
expect(subject.body.raw_source).to include('https://www.va.gov/resources/approved-fields-of-study-for-the-stem-scholarship?utm_source=confirmation_email&utm_medium=email&utm_campaign=stem_approved_programs')
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/mailers/create_excel_files_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe CreateExcelFilesMailer, type: %i[mailer aws_helpers] do
describe '#build' do
timestamp = Time.zone.now.strftime('%m%d%Y_%H%M%S')
filename = "22-10282_#{timestamp}.csv"
subject do
File.write("tmp/#{filename}", {})
described_class.build(filename).deliver_now
end
after do
FileUtils.rm_f("tmp/#{filename}")
end
context 'when sending emails' do
it 'sends the right email' do
date = Time.zone.now.strftime('%m/%d/%Y')
expect(subject.subject).to eq("(Staging) 22-10282 CSV file for #{date}")
expect(subject.content_type).to include('multipart/mixed')
expect(subject.content_type).to include('charset=UTF-8')
expect(subject.attachments.size).to eq(1)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/mailers/veteran_readiness_employment_mailer_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe VeteranReadinessEmploymentMailer, type: [:mailer] do
include ActionView::Helpers::TranslationHelper
let(:email_addr) { 'kcrawford@governmentcio.com' }
let(:current_date) { Time.current.in_time_zone('America/New_York').strftime('%m/%d/%Y') }
describe '#build' do
subject { described_class.build(user.participant_id, email_addr, routed_to_cmp).deliver_now }
context 'user is loa3 and has participant id' do
let(:user) { create(:evss_user, :loa3) }
context 'PDF is uploaded to VBMS' do
let(:routed_to_cmp) { false }
it 'includes all info' do
expect(subject.subject).to eq('VR&E Counseling Request Confirmation')
expect(subject.to).to eq(['kcrawford@governmentcio.com'])
expect(subject.body.raw_source).to include(
'Submitted Application',
"Veteran's PID: #{user.participant_id}",
'Type of Form Submitted: 28-1900',
"Submitted Date: #{current_date}"
)
end
end
context 'PDF is not uploaded to VBMS because it is down' do
let(:routed_to_cmp) { true }
it 'builds email correctly' do
expect(subject.subject).to eq('VR&E Counseling Request Confirmation')
expect(subject.to).to eq(['kcrawford@governmentcio.com'])
expect(subject.body.raw_source).to include(
'Submitted Application via VA.gov was not successful.',
'Application routed to the Centralized Mail Portal',
"Veteran's PID: #{user.participant_id}",
'Type of Form Submitted: 28-1900',
"Submitted Date: #{current_date}"
)
end
end
end
context 'user has no participant id' do
let(:user) { create(:unauthorized_evss_user) }
context 'PDF is uploaded to Central Mail' do
let(:routed_to_cmp) { true }
it 'includes all info' do
expect(subject.subject).to eq('VR&E Counseling Request Confirmation')
expect(subject.to).to eq(['kcrawford@governmentcio.com'])
expect(subject.body.raw_source).to include(
'Submitted Application via VA.gov was not successful.',
'Application routed to the Centralized Mail Portal',
"Veteran's PID:",
'Type of Form Submitted: 28-1900',
"Submitted Date: #{current_date}"
)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/stem_applicant_sco_mailer_preview.rb
|
# frozen_string_literal: true
class StemApplicantScoMailerPreview < ActionMailer::Preview
def build
return unless FeatureFlipper.staging_email?
applicant = SavedClaim::EducationBenefits::VA10203.last&.open_struct_form
ga_client_id = nil
StemApplicantScoMailer.build(applicant || fake_applicant, ga_client_id)
end
private
def fake_applicant
name = OpenStruct.new({
first: 'Test',
last: 'McTestyFace'
})
OpenStruct.new({
email: 'test@sample.com',
schoolEmailAddress: 'test@sample.edu',
schoolStudentId: '123',
schoolName: 'College of University',
veteranFullName: name
})
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/stem_applicant_denial_mailer_preview.rb
|
# frozen_string_literal: true
class StemApplicantDenialMailerPreview < ActionMailer::Preview
def build
return unless FeatureFlipper.staging_email?
time = Time.zone.now
claim = EducationBenefitsClaim.includes(:saved_claim, :education_stem_automated_decision).where(
processed_at: (time - 24.hours)..time,
saved_claims: {
form_id: '22-10203'
},
education_stem_automated_decisions: {
automated_decision_state: EducationStemAutomatedDecision::DENIED
}
)&.last
StemApplicantDenialMailer.build(claim, nil) if claim.present?
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/appeals_api_daily_error_report_mailer_preview.rb
|
# frozen_string_literal: true
class AppealsApiDailyErrorReportMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/appeals_api_daily_error_report_mailer/build
delegate :build, to: :'AppealsApi::DailyErrorReportMailer'
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/ch31_submissions_report_mailer_preview.rb
|
# frozen_string_literal: true
class Ch31SubmissionsReportMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/ch31_submissions_report_mailer
def build
claims = [create(:veteran_readiness_employment_claim, updated_at: '2017-07-26 00:00:00 UTC')]
Ch31SubmissionsReportMailer.build(claims)
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/school_certifying_officials_mailer_preview.rb
|
# frozen_string_literal: true
class SchoolCertifyingOfficialsMailerPreview < ActionMailer::Preview
def build
return unless FeatureFlipper.staging_email?
applicant = SavedClaim::EducationBenefits::VA10203.last&.open_struct_form
ga_client_id = nil
emails = recipients(params[:facility_code])
SchoolCertifyingOfficialsMailer.build(applicant || fake_applicant, emails, ga_client_id)
end
private
def recipients(facility_code)
return [] if facility_code.blank?
institution = GIDSRedis.new.get_institution_details({ id: facility_code })[:data][:attributes]
return [] if institution.blank?
scos = institution[:versioned_school_certifying_officials]
EducationForm::SendSchoolCertifyingOfficialsEmail.sco_emails(scos)
end
def fake_applicant
name = OpenStruct.new({
first: 'T',
last: 'McTestyFace'
})
OpenStruct.new({
email: 'test@sample.com',
schoolEmailAddress: nil,
schoolStudentId: nil,
veteranFullName: name
})
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/claims_api_submission_report_mailer_preview.rb
|
# frozen_string_literal: true
class ClaimsApiSubmissionReportMailerPreview < ActionMailer::Preview
def build
to = Time.zone.now
from = 1.month.ago
ClaimsApi::SubmissionReportMailer.build(
from,
to,
consumer_claims_totals: claims_totals,
poa_totals:,
ews_totals:,
itf_totals:
)
end
private
def unsuccessful_claims_submissions
[{ id: '019be853-fd70-4b65-b37b-c3f3842aaaca', status: 'errored', source: 'GDIT', created_at: 1.day.ago.to_s }]
end
def claims_totals
[
{ 'consumer 1' => { pending: 2, errored: 1, totals: 3, pact_count: 2 } },
{ 'consumer 2' => { pending: 3, errored: 3, totals: 6, pact_count: 1 } },
{ 'Totals' => { pending: 5, errored: 4, totals: 9, pact_count: 3 } }
]
end
def poa_totals
[
{ 'consumer 1' => { totals: 10, updated: 5, errored: 2, pending: 1, uploaded: 2 } },
{ 'consumer 2' => { totals: 8, updated: 3, errored: 2, pending: 1, uploaded: 2 } },
{ 'Totals' => { totals: 18, updated: 8, errored: 4, pending: 2, uploaded: 4 } }
]
end
def unsuccessful_poa_submissions
[
{ id: '61f6d6c9-b6ac-49c7-b1df-bccd065dbf9c', created_at: 1.day.ago.to_s },
{ id: '2753f720-d0a9-4b93-9721-eb3dd67fab9b', created_at: 1.day.ago.to_s }
]
end
def ews_totals
[
{ 'consumer 1' => { totals: 10, updated: 5, errored: 2, pending: 1, uploaded: 2 } },
{ 'consumer 2' => { totals: 8, updated: 3, errored: 2, pending: 1, uploaded: 2 } },
{ 'Totals' => { totals: 18, updated: 8, errored: 4, pending: 2, uploaded: 4 } }
]
end
def unsuccessful_evidence_waiver_submissions
[
{ id: '61f6d6c9-b6ac-49c7-b1df-bccd065dbf9c', created_at: 1.day.ago.to_s },
{ id: '2753f720-d0a9-4b93-9721-eb3dd67fab9b', created_at: 1.day.ago.to_s }
]
end
def itf_totals
[
{ 'consumer 1' => { totals: 2, submitted: 1, errored: 1 } },
{ 'consumer 2' => { totals: 1, submitted: 1, errored: 0 } },
{ 'Totals' => { totals: 3, submitted: 2, errored: 1 } }
]
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/appeals_api_decision_review_preview.rb
|
# frozen_string_literal: true
class AppealsApiDecisionReviewPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/appeals_api_decision_review
def build
to = Time.zone.now
from = Time.at(0).utc
AppealsApi::DecisionReviewMailer.build(date_from: from, date_to: to, recipients: ['hello@example.com'])
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/claims_api_unsuccessful_report_mailer_preview.rb
|
# frozen_string_literal: true
require './modules/claims_api/app/sidekiq/claims_api/reporting_base'
class ClaimsApiUnsuccessfulReportMailerPreview < ActionMailer::Preview
def build
to = Time.zone.now
from = 1.day.ago
ClaimsApi::UnsuccessfulReportMailer.build(
from,
to,
consumer_claims_totals: claims_totals,
unsuccessful_claims_submissions:,
unsuccessful_va_gov_claims_submissions:,
poa_totals:,
unsuccessful_poa_submissions:,
ews_totals:,
unsuccessful_evidence_waiver_submissions:,
itf_totals:
)
end
private
def unsuccessful_claims_submissions
reporting_base.unsuccessful_claims_submissions
end
def unsuccessful_va_gov_claims_submissions
reporting_base.unsuccessful_va_gov_claims_submissions
end
def claims_totals
call_factories
reporting_base.claims_totals
end
def poa_totals
reporting_base.poa_totals
end
def unsuccessful_poa_submissions
reporting_base.unsuccessful_poa_submissions
end
def ews_totals
reporting_base.ews_totals
end
def unsuccessful_evidence_waiver_submissions
reporting_base.unsuccessful_evidence_waiver_submissions
end
def itf_totals
reporting_base.itf_totals
end
def reporting_base
ClaimsApi::ReportingBase.new
end
def call_factories
make_claims
make_poas
make_ews_submissions
make_itfs
gather_consumers
end
def make_claims
# ClaimsApi::AutoEstablishedClaim.where(created_at: @from..@to).destroy_all
create(:auto_established_claim_v2, :errored)
create(:auto_established_claim, :errored)
create(:auto_established_claim_va_gov, :errored, created_at: Time.zone.now,
transaction_id: '467384632184')
create(:auto_established_claim_va_gov, :errored, created_at: Time.zone.now,
transaction_id: '467384632185')
create(:auto_established_claim_va_gov, :errored, created_at: Time.zone.now,
transaction_id: '467384632186')
create(:auto_established_claim_va_gov, :errored, created_at: Time.zone.now,
transaction_id: '467384632187')
create(:auto_established_claim_va_gov, :errored, created_at: Time.zone.now,
transaction_id: '467384632187')
create(:auto_established_claim_va_gov, created_at: Time.zone.now)
create(:auto_established_claim_v2, :errored)
create(:auto_established_claim_v2, :pending)
create(:auto_established_claim, :pending)
create(:auto_established_claim, :pending)
create(:auto_established_claim_with_supporting_documents, :pending)
create(:auto_established_claim, :pending)
end
def make_poas
# ClaimsApi::PowerOfAttorney.where(created_at: @from..@to).destroy_all
create(:power_of_attorney, :errored)
create(:power_of_attorney, :errored)
create(:power_of_attorney)
create(:power_of_attorney)
end
def make_ews_submissions
# ClaimsApi::EvidenceWaiverSubmission.where(created_at: @from..@to).destroy_all
create(:evidence_waiver_submission, :errored)
create(:evidence_waiver_submission)
create(:evidence_waiver_submission, :errored)
create(:evidence_waiver_submission)
end
def make_itfs
# ClaimsApi::IntentToFile.where(created_at: @from..@to).destroy_all
create(:intent_to_file, :itf_errored)
create(:intent_to_file, :itf_errored)
create(:intent_to_file)
end
def gather_consumers
@claims_consumers = ClaimsApi::AutoEstablishedClaim.where(created_at: @from..@to).pluck(:cid).uniq
@poa_consumers = ClaimsApi::PowerOfAttorney.where(created_at: @from..@to).pluck(:cid).uniq
@ews_consumers = ClaimsApi::EvidenceWaiverSubmission.where(created_at: @from..@to).pluck(:cid).uniq
@itf_consumers = ClaimsApi::IntentToFile.where(created_at: @from..@to).pluck(:cid).uniq
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/stem_applicant_confirmation_mailer_preview.rb
|
# frozen_string_literal: true
class StemApplicantConfirmationMailerPreview < ActionMailer::Preview
def build
return unless FeatureFlipper.staging_email?
return unless SavedClaim::EducationBenefits::VA10203.exists?(params[:claim_id])
claim = SavedClaim::EducationBenefits::VA10203.find(params[:claim_id])
ga_client_id = params.key?(:ga_client_id) ? params[:ga_client_id] : nil
StemApplicantConfirmationMailer.build(claim, ga_client_id) if claim.present?
end
end
|
0
|
code_files/vets-api-private/spec/mailers
|
code_files/vets-api-private/spec/mailers/previews/appeals_api_weekly_error_report_mailer_preview.rb
|
# frozen_string_literal: true
class AppealsApiWeeklyErrorReportMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/appeals_api_weekly_error_report_mailer/build
def build
recipients = Settings.modules_appeals_api.reports.weekly_error.recipients
AppealsApi::WeeklyErrorReportMailer.build(
date_from: Time.zone.now, date_to: 1.week.ago.beginning_of_day,
friendly_duration: 'Weekly', recipients:
)
end
end
|
0
|
code_files/vets-api-private/spec/config
|
code_files/vets-api-private/spec/config/initializers/staccato_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe Staccato do
it 'uses the google analytics url in settings' do
VCR.use_cassette('staccato/event', match_requests_on: %i[method uri]) do
Staccato.tracker('foo').event(
category: 'foo'
)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/secure_messaging_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
RSpec.describe 'secure_messaging rake tasks', type: :task do
before do
Rake.application.rake_require '../rakelib/secure_messaging'
Rake::Task.define_task(:environment)
end
describe 'sm:setup_test_user' do
context 'happy path' do
icn = '1234'
mhv_id = '22336066'
let(:mhv_id) { mhv_id }
let(:task) { Rake::Task['sm:setup_test_user'] }
let(:icn) { icn }
before do
task.reenable
ENV['user_number'] = '210'
ENV['mhv_id'] = mhv_id
# rubocop:disable RSpec/MessageChain
allow(Settings).to receive_message_chain(:betamocks, :cache_dir).and_return('../cache_dir')
allow(File).to receive(:read).and_return('{"uuid": "f37e9bef73df46a8a0c3f744e8f05185"}')
allow(MPI::Service).to receive_message_chain(:new, :find_profile_by_identifier)
.and_return(
double(
'profile',
profile: double(
'profile',
icn:
)
)
)
# rubocop:enable RSpec/MessageChain
end
it 'sets up a test user' do
expect(Rails.cache).to receive(:write).with(
"mhv_account_creation_#{icn}",
{ champ_va: true,
message: 'This cache entry was created by rakelib/secure_messaging.rake',
patient: true,
premium: true,
sm_account_created: true,
user_profile_id: mhv_id },
expires_in: 1.year
)
task.invoke
end
end
context 'invalid user' do
mhv_id = '22336066'
let(:mhv_id) { mhv_id }
let(:task) { Rake::Task['sm:setup_test_user'] }
before do
task.reenable
ENV['user_number'] = 'missing from mock data repo'
ENV['mhv_id'] = mhv_id
# rubocop:disable RSpec/MessageChain
allow(Settings).to receive_message_chain(:betamocks, :cache_dir).and_return('../x')
# rubocop:enable RSpec/MessageChain
end
it 'reports failure to locate mock user' do
expect { task.invoke }.to raise_error(
'No such file or directory @ rb_sysopen - ../x/credentials/idme/vetsgovusermissing from mock data repo.json'
).and output(
a_string_including('Encountered an error while trying to source ID.me UUID.')
).to_stdout
end
end
context 'fail to cache mhv account' do
icn = '1234'
mhv_id = '22336066'
let(:mhv_id) { mhv_id }
let(:task) { Rake::Task['sm:setup_test_user'] }
let(:icn) { icn }
before do
task.reenable
ENV['user_number'] = '210'
ENV['mhv_id'] = mhv_id
# rubocop:disable RSpec/MessageChain
allow(Settings).to receive_message_chain(:betamocks, :cache_dir).and_return('../cache_dir')
allow(File).to receive(:read).and_return('{"uuid": "f37e9bef73df46a8a0c3f744e8f05185"}')
allow(MPI::Service).to receive_message_chain(:new, :find_profile_by_identifier)
.and_return(
double(
'profile',
profile: double(
'profile',
icn:
)
)
)
allow(Rails.cache).to receive(:write).and_raise('Caching Error')
# rubocop:enable RSpec/MessageChain
end
it 'reports failure to cache mhv account' do
expect { task.invoke }.to raise_error('Caching Error').and output(
a_string_including("Something went wrong while trying to cache mhv_account for user with ICN: #{icn}.")
).to_stdout
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/decision_reviews_recovered_failures_remediation_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
describe 'decision_reviews:remediation rake tasks', type: :task do
before :all do
Rake.application.rake_require '../rakelib/decision_reviews_recovered_failures_remediation'
Rake.application.rake_require '../rakelib/decision_reviews_recovery_emails'
Rake::Task.define_task(:environment)
end
# Stub S3 uploads to prevent actual AWS calls during tests
before do
allow(Settings).to receive_messages(
reports: double(aws: double(
region: 'us-east-1',
access_key_id: 'test-key',
secret_access_key: 'test-secret',
bucket: 'test-bucket'
)),
vanotify: double(services: double(
benefits_decision_review: double(
api_key: 'test-api-key',
template_id: double(
evidence_recovery_email: 'evidence-template-id',
form_recovery_email: 'form-template-id'
)
)
))
)
# Stub S3 resource and operations
s3_resource = instance_double(Aws::S3::Resource)
s3_bucket = instance_double(Aws::S3::Bucket)
s3_object = instance_double(Aws::S3::Object)
allow(Aws::S3::Resource).to receive(:new).and_return(s3_resource)
allow(s3_resource).to receive(:bucket).and_return(s3_bucket)
allow(s3_bucket).to receive(:object).and_return(s3_object)
allow(s3_object).to receive(:put).and_return(true)
# Stub DecisionReviews constants for email sending tests
stub_const('DecisionReviews::V1::APPEAL_TYPE_TO_SERVICE_MAP', {
'HLR' => 'higher-level-review',
'NOD' => 'board-appeal',
'SC' => 'supplemental-claims'
})
end
let(:user_account) { create(:user_account) }
describe 'decision_reviews:remediation:clear_recovered_statuses' do
let(:saved_claim) do
create(:saved_claim_higher_level_review, metadata: {
status: 'error',
updatedAt: '2025-11-20T20:35:56.103Z',
createdAt: '2025-11-18T01:09:10.553Z',
uploads: []
}.to_json)
end
let(:appeal_submission) do
create(:appeal_submission,
saved_claim_hlr: saved_claim,
user_account:,
failure_notification_sent_at: 1.day.ago)
end
let(:run_rake_task) do
Rake::Task['decision_reviews:remediation:clear_recovered_statuses'].reenable
ENV['APPEAL_SUBMISSION_IDS'] = appeal_submission.id.to_s
ENV['DRY_RUN'] = 'true'
ENV.delete('LIGHTHOUSE_UPLOAD_IDS')
Rake.application.invoke_task 'decision_reviews:remediation:clear_recovered_statuses'
end
after do
ENV.delete('APPEAL_SUBMISSION_IDS')
ENV.delete('LIGHTHOUSE_UPLOAD_IDS')
ENV.delete('DRY_RUN')
end
context 'with no IDs provided' do
it 'exits with error message' do
ENV.delete('APPEAL_SUBMISSION_IDS')
ENV.delete('LIGHTHOUSE_UPLOAD_IDS')
# Use begin/rescue to catch SystemExit without propagating exit code
exit_raised = false
begin
silently do
Rake::Task['decision_reviews:remediation:clear_recovered_statuses'].reenable
Rake.application.invoke_task 'decision_reviews:remediation:clear_recovered_statuses'
end
rescue SystemExit
exit_raised = true
end
expect(exit_raised).to be true
end
end
context 'with valid appeal submission IDs in dry run mode' do
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
it 'does not modify the database' do
expect do
silently { run_rake_task }
end.not_to(change { saved_claim.reload.metadata })
end
end
context 'with valid appeal submission IDs in live mode' do
let(:run_live_task) do
Rake::Task['decision_reviews:remediation:clear_recovered_statuses'].reenable
ENV['APPEAL_SUBMISSION_IDS'] = appeal_submission.id.to_s
ENV['DRY_RUN'] = 'false'
Rake.application.invoke_task 'decision_reviews:remediation:clear_recovered_statuses'
end
it 'clears error status from metadata' do
silently { run_live_task }
metadata = JSON.parse(saved_claim.reload.metadata)
expect(metadata).not_to have_key('status')
expect(metadata).to have_key('uploads')
end
end
context 'with evidence upload IDs' do
let(:upload_saved_claim) do
create(:saved_claim_higher_level_review, metadata: {
status: 'complete',
updatedAt: '2025-11-20T20:35:56.103Z',
createdAt: '2025-11-18T01:09:10.553Z',
uploads: [
{ id: 'test-uuid-123',
status: 'error',
detail: 'Upstream status: Errors: ERR-EMMS-FAILED, Packet submission validation failed.',
createDate: '2025-11-15T23:07:40.892Z',
updateDate: '2025-11-15T23:07:40.892Z' }
]
}.to_json)
end
let(:appeal_submission_with_upload) do
create(:appeal_submission,
saved_claim_hlr: upload_saved_claim,
user_account:,
failure_notification_sent_at: 1.day.ago)
end
let(:evidence_upload) do
create(:appeal_submission_upload,
appeal_submission: appeal_submission_with_upload,
lighthouse_upload_id: 'test-uuid-123',
failure_notification_sent_at: 1.day.ago)
end
let(:run_evidence_task) do
Rake::Task['decision_reviews:remediation:clear_recovered_statuses'].reenable
ENV['LIGHTHOUSE_UPLOAD_IDS'] = evidence_upload.lighthouse_upload_id
ENV['DRY_RUN'] = 'false'
ENV.delete('APPEAL_SUBMISSION_IDS')
Rake.application.invoke_task 'decision_reviews:remediation:clear_recovered_statuses'
end
it 'clears error status from upload metadata' do
silently { run_evidence_task }
metadata = JSON.parse(upload_saved_claim.reload.metadata)
upload_entry = metadata['uploads'].first
expect(upload_entry['id']).to eq('test-uuid-123')
expect(upload_entry).not_to have_key('status')
expect(upload_entry).not_to have_key('detail')
end
end
end
describe 'decision_reviews:remediation:clear_november_2025_recovered_statuses' do
let(:run_rake_task) do
Rake::Task['decision_reviews:remediation:clear_november_2025_recovered_statuses'].reenable
ENV['DRY_RUN'] = 'true'
Rake.application.invoke_task 'decision_reviews:remediation:clear_november_2025_recovered_statuses'
end
after do
ENV.delete('DRY_RUN')
end
it 'runs without errors in dry run mode' do
expect { silently { run_rake_task } }.not_to raise_error
end
end
describe 'decision_reviews:remediation:send_evidence_recovery_emails' do
let(:saved_claim) { create(:saved_claim_higher_level_review) }
let(:appeal_submission) do
create(:appeal_submission,
saved_claim_hlr: saved_claim,
user_account:)
end
let(:evidence_upload) do
create(:appeal_submission_upload,
appeal_submission:,
lighthouse_upload_id: 'test-uuid-123',
failure_notification_sent_at: 1.day.ago)
end
let(:run_rake_task) do
Rake::Task['decision_reviews:remediation:send_evidence_recovery_emails'].reenable
ENV['LIGHTHOUSE_UPLOAD_IDS'] = evidence_upload.lighthouse_upload_id
ENV['DRY_RUN'] = 'true'
Rake.application.invoke_task 'decision_reviews:remediation:send_evidence_recovery_emails'
end
after do
ENV.delete('LIGHTHOUSE_UPLOAD_IDS')
ENV.delete('DRY_RUN')
end
context 'with no lighthouse upload IDs' do
it 'exits with error message' do
ENV.delete('LIGHTHOUSE_UPLOAD_IDS')
exit_raised = false
begin
silently do
Rake::Task['decision_reviews:remediation:send_evidence_recovery_emails'].reenable
Rake.application.invoke_task 'decision_reviews:remediation:send_evidence_recovery_emails'
end
rescue SystemExit
exit_raised = true
end
expect(exit_raised).to be true
end
end
context 'with valid inputs in dry run mode' do
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
it 'does not send any emails' do
expect_any_instance_of(VaNotify::Service).not_to receive(:send_email)
silently { run_rake_task }
end
end
context 'with valid inputs in live mode' do
let(:vanotify_service) { instance_double(VaNotify::Service) }
let(:email_address) { 'test@example.com' }
let(:run_live_rake_task) do
Rake::Task['decision_reviews:remediation:send_evidence_recovery_emails'].reenable
ENV['LIGHTHOUSE_UPLOAD_IDS'] = evidence_upload.lighthouse_upload_id
ENV['DRY_RUN'] = 'false'
Rake.application.invoke_task 'decision_reviews:remediation:send_evidence_recovery_emails'
end
before do
allow(VaNotify::Service).to receive(:new).and_return(vanotify_service)
allow(vanotify_service).to receive(:send_email).and_return({ 'id' => 'notification-123' })
# Stub MPI profile
mpi_profile = double(given_names: ['John'])
allow(appeal_submission).to receive_messages(get_mpi_profile: mpi_profile, current_email_address: email_address)
# Stub masked filename on upload
allow(evidence_upload).to receive(:masked_attachment_filename).and_return('eviXXXXXXce.pdf')
# Stub AppealSubmissionUpload.where to return our stubbed upload
# Need to stub the full chain: where().includes() and also .count
upload_relation = double('AppealSubmissionUpload::ActiveRecord_Relation')
allow(upload_relation).to receive_messages(includes: [evidence_upload], count: 1)
allow(AppealSubmissionUpload).to receive(:where).and_return(upload_relation)
end
it 'sends email via VA Notify with correct personalization' do
expect(vanotify_service).to receive(:send_email).with(
hash_including(
email_address:,
template_id: 'evidence-template-id',
personalisation: hash_including(
'first_name' => 'John',
'filename' => 'eviXXXXXXce.pdf',
'date_submitted' => kind_of(String)
)
)
)
silently { run_live_rake_task }
end
end
context 'when upload has no failure notification' do
let(:no_failure_upload) do
create(:appeal_submission_upload,
appeal_submission:,
lighthouse_upload_id: 'test-uuid-456',
failure_notification_sent_at: nil)
end
it 'skips the upload' do
ENV['LIGHTHOUSE_UPLOAD_IDS'] = no_failure_upload.lighthouse_upload_id
expect_any_instance_of(VaNotify::Service).not_to receive(:send_email)
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'decision_reviews:remediation:send_form_recovery_emails' do
let(:saved_claim) { create(:saved_claim_higher_level_review) }
let(:appeal_submission) do
create(:appeal_submission,
saved_claim_hlr: saved_claim,
user_account:,
failure_notification_sent_at: 1.day.ago)
end
let(:run_rake_task) do
Rake::Task['decision_reviews:remediation:send_form_recovery_emails'].reenable
ENV['APPEAL_SUBMISSION_IDS'] = appeal_submission.id.to_s
ENV['DRY_RUN'] = 'true'
Rake.application.invoke_task 'decision_reviews:remediation:send_form_recovery_emails'
end
after do
ENV.delete('APPEAL_SUBMISSION_IDS')
ENV.delete('DRY_RUN')
end
context 'with no appeal submission IDs' do
it 'exits with error message' do
ENV.delete('APPEAL_SUBMISSION_IDS')
exit_raised = false
begin
silently do
Rake::Task['decision_reviews:remediation:send_form_recovery_emails'].reenable
Rake.application.invoke_task 'decision_reviews:remediation:send_form_recovery_emails'
end
rescue SystemExit
exit_raised = true
end
expect(exit_raised).to be true
end
end
context 'with valid inputs in dry run mode' do
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
it 'does not send any emails' do
expect_any_instance_of(VaNotify::Service).not_to receive(:send_email)
silently { run_rake_task }
end
end
context 'with valid inputs in live mode' do
let(:vanotify_service) { instance_double(VaNotify::Service) }
let(:email_address) { 'test@example.com' }
let(:run_live_rake_task) do
Rake::Task['decision_reviews:remediation:send_form_recovery_emails'].reenable
ENV['APPEAL_SUBMISSION_IDS'] = appeal_submission.id.to_s
ENV['DRY_RUN'] = 'false'
Rake.application.invoke_task 'decision_reviews:remediation:send_form_recovery_emails'
end
before do
allow(VaNotify::Service).to receive(:new).and_return(vanotify_service)
allow(vanotify_service).to receive(:send_email).and_return({ 'id' => 'notification-123' })
# Stub MPI profile
mpi_profile = double(given_names: ['John'])
allow(appeal_submission).to receive_messages(get_mpi_profile: mpi_profile, current_email_address: email_address)
# Stub AppealSubmission.where to return our stubbed submission
# Need to stub the full chain: where().includes()
submission_relation = double('AppealSubmission::ActiveRecord_Relation')
allow(submission_relation).to receive_messages(includes: [appeal_submission], count: 1)
allow(AppealSubmission).to receive(:where).and_return(submission_relation)
end
it 'sends email via VA Notify with correct personalization' do
expect(vanotify_service).to receive(:send_email).with(
hash_including(
email_address:,
template_id: 'form-template-id',
personalisation: hash_including(
'first_name' => 'John',
'decision_review_type' => 'Notice of Disagreement (Board Appeal)',
'decision_review_form_id' => 'VA Form 10182',
'date_submitted' => kind_of(String)
)
)
)
silently { run_live_rake_task }
end
end
context 'when submission has no failure notification' do
let(:no_failure_submission) do
create(:appeal_submission,
saved_claim_hlr: saved_claim,
user_account:,
failure_notification_sent_at: nil)
end
it 'skips the submission' do
ENV['APPEAL_SUBMISSION_IDS'] = no_failure_submission.id.to_s
expect_any_instance_of(VaNotify::Service).not_to receive(:send_email)
expect { silently { run_rake_task } }.not_to raise_error
end
end
context 'S3 upload' do
let(:s3_object) { instance_double(Aws::S3::Object) }
before do
# More specific S3 stubbing for this test
s3_resource = instance_double(Aws::S3::Resource)
s3_bucket = instance_double(Aws::S3::Bucket)
allow(Aws::S3::Resource).to receive(:new).and_return(s3_resource)
allow(s3_resource).to receive(:bucket).and_return(s3_bucket)
allow(s3_bucket).to receive(:object).and_return(s3_object)
allow(s3_object).to receive(:put).and_return(true)
end
it 'uploads results to S3 by default' do
expect(s3_object).to receive(:put).with(
hash_including(
content_type: 'text/plain'
)
)
silently { run_rake_task }
end
it 'skips S3 upload when UPLOAD_TO_S3=false' do
ENV['UPLOAD_TO_S3'] = 'false'
expect(s3_object).not_to receive(:put)
silently { run_rake_task }
ENV.delete('UPLOAD_TO_S3')
end
end
end
describe 'decision_reviews:remediation:send_november_2025_recovery_emails' do
let(:saved_claim) { create(:saved_claim_higher_level_review) }
let(:appeal_submission) do
create(:appeal_submission,
saved_claim_hlr: saved_claim,
user_account:,
failure_notification_sent_at: 1.day.ago)
end
let(:evidence_upload) do
create(:appeal_submission_upload,
appeal_submission:,
lighthouse_upload_id: 'test-uuid-123',
failure_notification_sent_at: 1.day.ago)
end
let(:run_rake_task) do
Rake::Task['decision_reviews:remediation:send_november_2025_recovery_emails'].reenable
ENV['DRY_RUN'] = 'true'
Rake.application.invoke_task 'decision_reviews:remediation:send_november_2025_recovery_emails'
end
after do
ENV.delete('DRY_RUN')
ENV.delete('UPLOAD_TO_S3')
end
context 'with dry run mode' do
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
it 'does not send any emails' do
expect_any_instance_of(VaNotify::Service).not_to receive(:send_email)
silently { run_rake_task }
end
end
context 'S3 upload' do
let(:s3_object) { instance_double(Aws::S3::Object) }
before do
s3_resource = instance_double(Aws::S3::Resource)
s3_bucket = instance_double(Aws::S3::Bucket)
allow(Aws::S3::Resource).to receive(:new).and_return(s3_resource)
allow(s3_resource).to receive(:bucket).and_return(s3_bucket)
allow(s3_bucket).to receive(:object).and_return(s3_object)
allow(s3_object).to receive(:put).and_return(true)
end
it 'uploads combined results to S3 by default' do
expect(s3_object).to receive(:put).with(
hash_including(
content_type: 'text/plain'
)
)
silently { run_rake_task }
end
it 'skips S3 upload when UPLOAD_TO_S3=false' do
ENV['UPLOAD_TO_S3'] = 'false'
expect(s3_object).not_to receive(:put)
silently { run_rake_task }
end
end
end
end
# Helper to suppress verbose logging during tests
def silently
# Store the original stderr and stdout in order to restore them later
@original_stderr = $stderr
@original_stdout = $stdout
# Redirect stderr and stdout
$stderr = $stdout = StringIO.new
yield
$stderr = @original_stderr
$stdout = @original_stdout
@original_stderr = nil
@original_stdout = nil
end
def capture_stdout
original_stdout = $stdout
$stdout = StringIO.new
yield
$stdout.string
ensure
$stdout = original_stdout
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/form526_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
require 'olive_branch_patch'
describe 'form526 rake tasks', type: :request do
let(:user) { build(:disabilities_compensation_user) }
let(:headers) { { 'CONTENT_TYPE' => 'application/json' } }
let(:headers_with_camel) { headers.merge('HTTP_X_KEY_INFLECTION' => 'camel') }
let(:in_progress_form526_original) do
JSON.parse(File.read(
'spec/support/disability_compensation_form/526_in_progress_form_maixmal.json'
))
end
let!(:in_progress_form) do
form_json = JSON.parse(File.read('spec/support/disability_compensation_form/526_in_progress_form_maixmal.json'))
create(:in_progress_form,
user_uuid: user.uuid,
form_id: '21-526EZ',
form_data: to_case(:dasherize, to_case(:camelize, to_case(:dasherize, form_json['formData']))),
metadata: to_case(:dasherize, to_case(:camelize, to_case(:dasherize, form_json['metadata']))))
end
before :all do
Rake.application.rake_require '../rakelib/form526'
Rake::Task.define_task(:environment)
end
describe 'rake form526:convert_sip_data' do
let(:path_to_csv) { 'tmp/rake_task_output.csv' }
let :run_rake_task do
Rake::Task['form526:convert_sip_data'].reenable
Rake.application.invoke_task "form526:convert_sip_data[#{path_to_csv}]"
end
it 'fixes the form data with the rake task' do
# corrupted before, with snake case keys in db
form_data_json = JSON.parse(in_progress_form.form_data)
expect(form_data_json['va_treatment_facilities'].first['treated_disability_names'].keys).to(
include('aaaaa camelcase nightmareweasdf123_asdf')
)
expect(form_data_json['view:is_pow']['pow_disabilities'].keys).to(
include('aaaaa camelcase nightmareweasdf123_asdf')
)
expect { run_rake_task }.not_to raise_error
# fixed, after with camel case in db
fixed_form = InProgressForm.find(in_progress_form.id).form_data
fixed_form_json = JSON.parse(fixed_form)
expect(fixed_form_json['vaTreatmentFacilities'].first['treatedDisabilityNames'].keys).to(
include('aaaaa camelcase nightmareweasdf-123--asdf')
)
expect(fixed_form_json['view:isPow']['powDisabilities'].keys).to(
include('aaaaa camelcase nightmareweasdf-123--asdf')
)
expect(fixed_form).not_to include('aaaaa camel_case nightmare_w_easdf123_asdf')
end
it 'returns the data that was sent from the FE to the BE unharmed' do
sign_in_as(user)
put '/v0/in_progress_forms/21-526EZ', params: in_progress_form.to_json, headers: headers_with_camel
run_rake_task
get('/v0/in_progress_forms/21-526EZ', headers:)
response_json = JSON.parse(response.body)
expect(response_json['formData']).to eq(in_progress_form526_original['formData'])
end
end
describe 'rake form526:submissions' do
let!(:form526_submission) { create(:form526_submission, :with_mixed_status) }
def run_rake_task(args_string)
Rake::Task['form526:submissions'].reenable
Rake.application.invoke_task "form526:submissions[#{args_string}]"
end
context 'runs without errors' do
[
['', 'no args'],
['2020-12-25', 'just a start date'],
[',2020-12-25', 'just an end date'],
['2020-12-24,2020-12-25', 'two dates'],
['bdd', 'bdd stats mode']
].each do |(args_string, desc)|
it desc do
expect { silently { run_rake_task(args_string) } }.not_to raise_error
end
end
end
end
describe 'rake form526:errors' do
let!(:form526_submission) { create(:form526_submission, :with_one_failed_job) }
let :run_rake_task do
Rake::Task['form526:errors'].reenable
Rake.application.invoke_task 'form526:errors'
end
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
end
describe 'rake form526:submission' do
let!(:form526_submission) { create(:form526_submission, :with_mixed_status) }
let :run_rake_task do
Rake::Task['form526:submission'].reenable
Rake.application.invoke_task "form526:submission[#{form526_submission.id}]"
end
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
end
describe 'rake form526:mpi' do
let(:submission) { create(:form526_submission) }
let(:profile) { build(:mpi_profile) }
let(:profile_response) { create(:find_profile_response, profile:) }
let(:run_rake_task) do
Rake::Task['form526:mpi'].reenable
Rake.application.invoke_task "form526:mpi[#{submission.id}]"
end
it 'runs without errors' do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_edipi).and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
expect { silently { run_rake_task } }.not_to raise_error
end
end
describe 'rake form526:pif_errors' do
let!(:submission) { create(:form526_submission, :with_pif_in_use_error) }
let :run_rake_task do
Rake::Task['form526:pif_errors'].reenable
Rake.application.invoke_task 'form526:pif_errors'
end
it 'runs without errors' do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
def silently
# Store the original stderr and stdout in order to restore them later
@original_stderr = $stderr
@original_stdout = $stdout
# Redirect stderr and stdout
$stderr = $stdout = StringIO.new
yield
$stderr = @original_stderr
$stdout = @original_stdout
@original_stderr = nil
@original_stdout = nil
end
def to_case(method, val)
if method == :dasherize
val.deep_transform_keys!(&:underscore)
else
OliveBranch::Transformations.transform(
val,
OliveBranch::Transformations.method(method)
)
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/user_credential_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
describe 'user_credential rake tasks' do # rubocop:disable RSpec/DescribeClass
let(:user_account) { create(:user_account) }
let(:icn) { user_account.icn }
let(:user_verification) { create(:logingov_user_verification, user_account:) }
let(:type) { user_verification.credential_type }
let(:credential_id) { user_verification.credential_identifier }
let(:linked_user_verification) { create(:idme_user_verification, user_account:) }
let(:linked_type) { linked_user_verification.credential_type }
let(:linked_credential_id) { linked_user_verification.credential_identifier }
let(:requested_by) { 'some-name' }
before :all do
Rake.application.rake_require '../rakelib/prod/user_credential'
Rake::Task.define_task(:environment)
end
context 'argument validations' do
let(:task) { Rake::Task['user_credential:lock'] }
before { task.reenable }
context 'when a required argument is missing' do
let(:expected_output) { '[UserCredential::Lock] failed - Missing required arguments' }
it 'raises an error' do
expect { task.invoke }.to output("#{expected_output}\n").to_stdout
end
end
context 'rwhen type argument is invalid' do
let(:expected_output) { '[UserCredential::Lock] failed - Invalid type' }
it 'raises an error' do
expect { task.invoke('invalid', credential_id, requested_by) }.to output("#{expected_output}\n").to_stdout
end
end
end
context 'single credential changes' do
let(:expected_output) do
"#{namespace} rake task start, context: {\"type\":\"#{type}\",\"credential_id\":\"#{credential_id}\"," \
"\"requested_by\":\"#{requested_by}\"}\n" \
"#{namespace} credential #{action}, context: {\"type\":\"#{type}\",\"credential_id\":\"#{credential_id}\"," \
"\"requested_by\":\"#{requested_by}\",\"locked\":#{locked}}\n" \
"#{namespace} rake task complete, context: {\"type\":\"#{type}\",\"credential_id\":\"#{credential_id}\"," \
"\"requested_by\":\"#{requested_by}\"}\n"
end
describe 'user_credential:lock' do
let(:task) { Rake::Task['user_credential:lock'] }
let(:namespace) { '[UserCredential::Lock]' }
let(:action) { 'lock' }
let(:locked) { true }
before do
user_verification.unlock!
task.reenable
end
it 'locks the credential & return the credential type & uuid when successful' do
expect(user_verification.locked).to be_falsey
expect { task.invoke(type, credential_id, requested_by) }.to output(expected_output).to_stdout
expect(user_verification.reload.locked).to be_truthy
end
end
describe 'user_credential:unlock' do
let(:task) { Rake::Task['user_credential:unlock'] }
let(:namespace) { '[UserCredential::Unlock]' }
let(:action) { 'unlock' }
let(:locked) { false }
before { user_verification.lock! }
it 'unlocks the credential & return the credential type & uuid when successful' do
expect(user_verification.locked).to be_truthy
expect { task.invoke(type, credential_id, requested_by) }.to output(expected_output).to_stdout
expect(user_verification.reload.locked).to be_falsey
end
end
end
context 'account-wide credential changes' do
let(:expected_output) do
[
"#{namespace} rake task start, context: {\"icn\":\"#{icn}\",\"requested_by\":\"#{requested_by}\"}",
"#{namespace} credential #{action}, context: {\"icn\":\"#{icn}\",\"requested_by\":\"#{requested_by}\"," \
"\"type\":\"#{type}\",\"credential_id\":\"#{credential_id}\",\"locked\":#{locked}}",
"#{namespace} credential #{action}, context: {\"icn\":\"#{icn}\",\"requested_by\":\"#{requested_by}\"," \
"\"type\":\"#{linked_type}\",\"credential_id\":\"#{linked_credential_id}\",\"locked\":#{locked}}",
"#{namespace} rake task complete, context: {\"icn\":\"#{icn}\",\"requested_by\":\"#{requested_by}\"}"
].sort
end
describe 'user_credential:lock_all' do
let(:task) { Rake::Task['user_credential:lock_all'] }
let(:namespace) { '[UserCredential::LockAll]' }
let(:action) { 'lock' }
let(:locked) { true }
before do
user_verification.unlock!
linked_user_verification.unlock!
end
it 'locks all credentials for a user account & return the ICN when successful' do
sorted_output = []
expect do
task.invoke(icn, requested_by)
sorted_output = $stdout.string.split("\n").map(&:strip).sort
end.to output.to_stdout
expect(sorted_output).to eq(expected_output)
expect(user_verification.reload.locked).to be_truthy
expect(linked_user_verification.reload.locked).to be_truthy
end
end
describe 'user_credential:unlock_all' do
let(:task) { Rake::Task['user_credential:unlock_all'] }
let(:namespace) { '[UserCredential::UnlockAll]' }
let(:action) { 'unlock' }
let(:locked) { false }
before do
user_verification.lock!
linked_user_verification.lock!
end
it 'unlocks all credentials for a user account & return the ICN when successful' do
sorted_output = []
expect do
task.invoke(icn, requested_by)
sorted_output = $stdout.string.split("\n").map(&:strip).sort
end.to output.to_stdout
expect(sorted_output).to eq(expected_output)
expect(user_verification.reload.locked).to be_falsey
expect(linked_user_verification.reload.locked).to be_falsey
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/jobs_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
describe 'jobs rake tasks', type: :request do
before :all do
Rake.application.rake_require '../rakelib/jobs'
Rake::Task.define_task(:environment)
end
describe 'rake jobs:reset_daily_spool_files_for_today' do
let :run_rake_task do
Rake::Task['jobs:reset_daily_spool_files_for_today'].reenable
Rake.application.invoke_task 'jobs:reset_daily_spool_files_for_today'
end
it 'runs without errors in non production environments' do
allow(Settings).to receive(:vsp_environment).and_return('staging')
expect { run_rake_task }.not_to raise_error
end
it 'raises an exception if the environment is production' do
allow(Settings).to receive(:vsp_environment).and_return('production')
expect { run_rake_task }.to raise_error Common::Exceptions::Unauthorized
end
it 'deletes spool file event rows created today' do
rpo = EducationForm::EducationFacility::FACILITY_IDS[:western]
yday = Time.zone.yesterday
create(:spool_file_event, filename: "#{rpo}_#{yday.strftime('%m%d%Y_%H%M%S')}_vetsgov.spl", created_at: yday)
create(:spool_file_event, :successful)
expect { run_rake_task }.to change(SpoolFileEvent, :count).by(-1)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/rakelib/vet360_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
describe 'vet360 rake tasks' do
before :all do
Rake.application.rake_require '../rakelib/vet360'
Rake::Task.define_task(:environment)
end
before do
# Prevents cross-pollination between tests
ENV['VET360_RAKE_DATA'] = nil
end
service = VAProfile::ContactInformation::V2::Service
cassette_path = 'va_profile/v2/contact_information'
describe 'rake vet360:get_person' do
let :run_rake_task do
Rake::Task['vet360:get_person'].reenable
Rake.application.invoke_task 'vet360:get_person[1]'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:get_person)
VCR.use_cassette("#{cassette_path}/person", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:get_email_transaction_status' do
let :run_rake_task do
Rake::Task['vet360:get_email_transaction_status'].reenable
Rake.application.invoke_task 'vet360:get_email_transaction_status[1,786efe0e-fd20-4da2-9019-0c00540dba4d]'
end
let :fail_rake_task do
Rake::Task['vet360:get_email_transaction_status'].reenable
Rake.application.invoke_task 'vet360:get_email_transaction_status[]'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:get_email_transaction_status)
VCR.use_cassette("#{cassette_path}/email_transaction_status", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
it 'aborts' do
expect_any_instance_of(service).not_to receive(:get_email_transaction_status)
end
end
describe 'rake vet360:get_address_transaction_status' do
let :run_rake_task do
Rake::Task['vet360:get_address_transaction_status'].reenable
Rake.application.invoke_task 'vet360:get_address_transaction_status[1,0faf342f-5966-4d3f-8b10-5e9f911d07d2]'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:get_address_transaction_status)
VCR.use_cassette("#{cassette_path}/address_transaction_status", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:get_telephone_transaction_status' do
let :run_rake_task do
Rake::Task['vet360:get_telephone_transaction_status'].reenable
Rake.application.invoke_task 'vet360:get_telephone_transaction_status[1,a50193df-f4d5-4b6a-b53d-36fed2db1a15]'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:get_telephone_transaction_status)
VCR.use_cassette("#{cassette_path}/telephone_transaction_status", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:put_email' do
let :run_rake_task do
data = '{"email_address_text":"person42@example.com","email_id":42,' \
'"originating_source_system":"VETSGOV","source_date":"2018-04-09T11:52:03.000-06:00","vet360_id":"1"}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:put_email'].reenable
Rake.application.invoke_task 'vet360:put_email'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:put_email)
VCR.use_cassette("#{cassette_path}/put_email_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:put_telephone' do
let :run_rake_task do
data = '{"area_code":"303","country_code":"1","international_indicator":false,' \
'"originating_source_system":"VETSGOV","phone_number":"5551235","phone_number_ext":null,' \
'"phone_type":"MOBILE","source_date":"2018-04-09T11:52:03.000-06:00","telephone_id":1299,' \
'"tty_ind":true,"vet360_id":"1","voice_mail_acceptable_ind":true}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:put_telephone'].reenable
Rake.application.invoke_task 'vet360:put_telephone'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:put_telephone)
VCR.use_cassette("#{cassette_path}/put_telephone_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:put_address' do
let :run_rake_task do
data = '{"address_id":437,"address_line1":"1494 Martin Luther King Rd","address_line2":null,' \
'"address_line3":null,"address_pou":"RESIDENCE/CHOICE","address_type":"domestic","city_name":"Fulton",' \
'"country_code_ios2":null,"country_code_iso3":null,"country_name":"USA","county":{"county_code":null,' \
'"county_name":null},"int_postal_code":null,"province_name":null,"state_code":"MS","zip_code5":"38843",' \
'"zip_code4":null,"originating_source_system":"VETSGOV","source_date":"2018-04-09T11:52:03.000-06:00",' \
'"vet360_id":"1"}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:put_address'].reenable
Rake.application.invoke_task 'vet360:put_address'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:put_address)
VCR.use_cassette("#{cassette_path}/put_address_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:post_email' do
let :run_rake_task do
data = '{"email_address_text":"person42@example.com","email_id":null,"originating_source_system":"VETSGOV",' \
'"source_date":"2018-04-09T11:52:03.000-06:00","vet360_id":"1"}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:post_email'].reenable
Rake.application.invoke_task 'vet360:post_email'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:post_email)
VCR.use_cassette("#{cassette_path}/post_email_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:post_telephone' do
let :run_rake_task do
data = '{"area_code":"303","country_code":"1","international_indicator":false,' \
'"originating_source_system":"VETSGOV","phone_number":"5551234","phone_number_ext":null,' \
'"phone_type":"MOBILE","source_date":"2018-04-09T11:52:03.000-06:00","telephone_id":null,' \
'"tty_ind":true,"vet360_id":"1","voice_mail_acceptable_ind":true}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:post_telephone'].reenable
Rake.application.invoke_task 'vet360:post_telephone'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:post_telephone)
VCR.use_cassette("#{cassette_path}/post_telephone_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:post_address' do
let :run_rake_task do
data = '{"address_id":null,"address_line1":"1493 Martin Luther King Rd","address_line2":null,' \
'"address_line3":null,"address_pou":"RESIDENCE","address_type":"domestic","city_name":"Fulton",' \
'"country":{"country_code_iso2":null,"country_code_iso3":"USA","country_name":"USA"},' \
'"county":{"county_code":null,"county_name":null},' \
'"int_postal_code":null,"province":{"province_name":null,"province_code":null},' \
'"state":{"state_name":"null","state_code":"MS"},"int_postal_code":null,"zip_code5":"38843",' \
'"zip_code4":null,"originating_source_system":"VETSGOV","source_date":"2024-08-27T18:51:06.000Z",' \
'"effective_start_date":"2024-08-27T18:51:06.000Z","effective_end_date":null}'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:post_address'].reenable
Rake.application.invoke_task 'vet360:post_address'
end
it 'runs without errors' do
expect_any_instance_of(service).to receive(:post_address)
VCR.use_cassette("#{cassette_path}/post_address_success", VCR::MATCH_EVERYTHING) do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
describe 'rake vet360:prep_error_codes' do
let :run_rake_task do
Rake::Task['vet360:prep_error_codes'].reenable
Rake.application.invoke_task 'vet360:prep_error_codes'
end
it 'runs without errors' do
expect_any_instance_of(VAProfile::Exceptions::Builder).to receive(:construct_exceptions_from_csv)
expect { silently { run_rake_task } }.not_to raise_error
end
end
describe 'rake vet360:init_vet360_id' do
let :run_rake_task do
data = '123456,1312312'
ENV['VET360_RAKE_DATA'] = data
Rake::Task['vet360:init_vet360_id'].reenable
Rake.application.invoke_task 'vet360:init_vet360_id'
end
it 'runs without errors' do
VCR.use_cassette('va_profile/v2/person/init_vet360_id_success') do
expect { silently { run_rake_task } }.not_to raise_error
end
end
end
end
def silently
# Store the original stderr and stdout in order to restore them later
@original_stderr = $stderr
@original_stdout = $stdout
# Redirect stderr and stdout
$stderr = $stdout = StringIO.new
yield
$stderr = @original_stderr
$stdout = @original_stdout
@original_stderr = nil
@original_stdout = nil
end
|
0
|
code_files/vets-api-private/spec/rakelib
|
code_files/vets-api-private/spec/rakelib/piilog_repl/piilog_helpers_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require_relative '../../../rakelib/piilog_repl/piilog_helpers'
Q = PersonalInformationLogQueryBuilder
describe PersonalInformationLogQueryBuilder do
[
[
'string/symbol args* narrow the error_class (*most string args)',
Q.call(:hlr, :nod),
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
" WHERE (error_class ILIKE ANY (array['%hlr%', '%nod%']))"
],
[
'a single date narrows the query to just that day',
Q.call(:hlr, '2021-04-01'),
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
" WHERE (error_class ILIKE ANY (array['%hlr%']))" \
" AND \"personal_information_logs\".\"created_at\" BETWEEN '2021-04-01 00:00:00' AND '2021-04-01 23:59:59.999999'"
],
[
'can take a date range, and does first_time.start_of_day second_time.end_of_day',
Q.call('2021-03-01', '2021-03-31'),
'SELECT "personal_information_logs".* FROM "personal_information_logs" WHERE' \
' "personal_information_logs"."created_at" BETWEEN \'2021-03-01 00:00:00\' AND \'2021-03-31 23:59:59.999999\''
],
[
"argument order doesn't matter (2 time arguments can be specified --unrelated args can be inbetween them)",
Q.call('2021-03-01', :hlr, '2021-03-31'),
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
" WHERE (error_class ILIKE ANY (array['%hlr%']))" \
" AND \"personal_information_logs\".\"created_at\" BETWEEN '2021-03-01 00:00:00' AND '2021-03-31 23:59:59.999999'"
],
[
'specific times/dates are allowed',
Q.call('2021-03-01T12:00Z', Time.zone.parse('2021-04-01T14:00:00Z') - 5.minutes),
'SELECT "personal_information_logs".* FROM "personal_information_logs" WHERE' \
" \"personal_information_logs\".\"created_at\" BETWEEN '2021-03-01 12:00:00' AND '2021-04-01 13:55:00'"
],
[
'durations are allowed',
Q.call(30.days, '2021-03-01'), # 30 days before March 1
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
' WHERE "personal_information_logs"."created_at"' \
" BETWEEN '2021-01-30 23:59:59.999999' AND '2021-03-01 23:59:59.999999'"
],
[
'times ranges can be open ended with nil',
Q.call('2021-03-01', nil),
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
" WHERE (created_at >= '2021-03-01 00:00:00')"
],
[
'kwargs work like a normal "where" call',
Q.call(:hlr, updated_at: ['2021-04-02'.in_time_zone.all_day]),
'SELECT "personal_information_logs".* FROM "personal_information_logs"' \
' WHERE "personal_information_logs"."updated_at" BETWEEN' \
" '2021-04-02 00:00:00' AND '2021-04-02 23:59:59.999999' AND (error_class ILIKE ANY (array['%hlr%']))"
]
].each do |desc, relation, expected_sql|
it(desc) { expect(relation.to_sql).to eq expected_sql }
end
end
|
0
|
code_files/vets-api-private/spec/rakelib
|
code_files/vets-api-private/spec/rakelib/fixtures/rspec.xml
|
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="rspec" tests="803" skipped="0" failures="0" errors="0" time="156.211777" timestamp="2021-12-14T15:14:14+00:00" hostname="ef62748a302f">
<properties><property name="seed" value="24550"/></properties>
<testcase classname="modules.check_in.spec.services.v2.chip.service_spec" name="V2::Chip::Service#create_check_in when token is not present returns unauthorized" file="./modules/check_in/spec/services/v2/chip/service_spec.rb" time="0.052078"></testcase>
<testcase classname="modules.check_in.spec.services.v2.chip.service_spec" name="V2::Chip::Service#create_check_in when token is already present returns correct response" file="./modules/check_in/spec/services/v2/chip/service_spec.rb" time="0.037033"></testcase>
<testcase classname="spec.lib.sidekiq_stats_instrumentation.server_middleware_spec" name="SidekiqStatsInstrumentation::ServerMiddleware#call measures job runtime" file="./spec/lib/sidekiq_stats_instrumentation/server_middleware_spec.rb" time="0.095769"></testcase>
<testcase classname="spec.lib.sidekiq_stats_instrumentation.server_middleware_spec" name="SidekiqStatsInstrumentation::ServerMiddleware#call increments dequeue counter" file="./spec/lib/sidekiq_stats_instrumentation/server_middleware_spec.rb" time="0.050840"></testcase>
<testcase classname="modules.appeals_api.spec.requests.v2.legacy_appeals_controller_spec" name="AppealsApi::V2::DecisionReviews::LegacyAppealsController#index when only ssn provided when veteran record does not exist returns a 404" file="./modules/appeals_api/spec/requests/v2/legacy_appeals_controller_spec.rb" time="0.061686"></testcase>
<testcase classname="modules.appeals_api.spec.requests.v2.legacy_appeals_controller_spec" name="AppealsApi::V2::DecisionReviews::LegacyAppealsController#index when only ssn provided when Veteran has no legacy appeals returns an empty array" file="./modules/appeals_api/spec/requests/v2/legacy_appeals_controller_spec.rb" time="0.067544"></testcase>
</testsuite>
|
0
|
code_files/vets-api-private/spec/rakelib
|
code_files/vets-api-private/spec/rakelib/fixtures/index.html
|
<!DOCTYPE html>
<head>
<title>Code coverage for Src</title>
</head>
<body>
<h2>
<span class="group_name">All Files</span>
(<span class="covered_percent">
<span class="green">
97.65%
</span>
</span>
covered at
<span class="covered_strength">
<span class="green">
143.59
</span>
</span> hits/line
)
</h2>
<h2>
<span class="group_name">Controllers</span>
(<span class="covered_percent">
<span class="green">
97.04%
</span>
</span>
covered at
<span class="covered_strength">
<span class="green">
32.81
</span>
</span> hits/line
)</h2></body>
</html>
|
0
|
code_files/vets-api-private/spec/rakelib
|
code_files/vets-api-private/spec/rakelib/fixtures/rspec_failure.xml
|
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="rspec11" tests="1224" skipped="1" failures="1" errors="0" time="118.212155" timestamp="2021-12-14T15:14:14+00:00" hostname="ef62748a302f">
<properties><property name="seed" value="8056"/></properties>
<testcase classname="spec.rakelib.form526_spec" name="form526 rake tasks rake form526:submissions runs without errors just an end date" file="./spec/rakelib/form526_spec.rb" time="0.493059"></testcase>
<testcase classname="spec.jobs.in_progress_form_cleaner_spec" name="InProgressFormCleaner#perform when there is a form526 record older than 365 days deletes the record" file="./spec/sidekiq/in_progress_form_cleaner_spec.rb" time="0.117146"><failure message="expected `InProgressForm.count` to have changed by -1, but was changed by 0" type="RSpec::Expectations::ExpectationNotMetError">Failure/Error: expect { subject.perform }.to change(InProgressForm, :count).by(-1)
expected `InProgressForm.count` to have changed by -1, but was changed by 0
/usr/local/bundle/gems/super_diff-0.8.0/lib/super_diff/rspec/monkey_patches.rb:45:in `handle_failure'
/usr/local/bundle/gems/rspec-retry-0.6.2/lib/rspec/retry.rb:37:in `block (2 levels) in setup'</failure></testcase>
<testcase classname="spec.jobs.in_progress_form_cleaner_spec" name="InProgressFormCleaner#perform when there is a form526 record older than 60 days does not delete the record" file="./spec/sidekiq/in_progress_form_cleaner_spec.rb" time="0.041648"></testcase>
</testsuite>
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/evidence_submission_poll_store_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EvidenceSubmissionPollStore, type: :model do
subject { described_class.new(claim_id: '123456', request_ids: [111_111, 222_222, 333_333]) }
describe 'configuration' do
it 'has a configured redis namespace instance' do
expect(described_class.redis_namespace).to be_a(Redis::Namespace)
expect(described_class.redis_namespace.namespace).to eq('evidence-submission-poll')
end
it 'has a configured TTL of 60 seconds' do
expect(described_class.redis_namespace_ttl).to eq(60)
end
it 'uses claim_id as the redis key' do
expect(described_class.redis_namespace_key).to eq(:claim_id)
end
end
describe 'validations' do
it 'requires claim_id' do
record = described_class.new(request_ids: [111_111])
expect(record).not_to be_valid
expect(record.errors[:claim_id]).to include("can't be blank")
end
it 'requires request_ids' do
record = described_class.new(claim_id: '123456')
expect(record).not_to be_valid
expect(record.errors[:request_ids]).to include("can't be blank")
end
it 'is valid with all required attributes' do
expect(subject).to be_valid
end
end
describe '.find' do
it 'finds deserialized record in redis' do
subject.save
found = described_class.find('123456')
expect(found).to be_a(described_class)
expect(found.claim_id).to eq('123456')
expect(found.request_ids).to eq([111_111, 222_222, 333_333])
end
it 'returns nil when key does not exist' do
found = described_class.find('nonexistent')
expect(found).to be_nil
end
end
describe '.create' do
it 'creates and saves a new record' do
record = described_class.create(claim_id: '789012', request_ids: [444_444, 555_555])
expect(record).to be_persisted
expect(described_class.find('789012')).to be_present
end
end
describe '#save' do
it 'saves entry with namespace' do
subject.save
expect(subject.redis_namespace.redis.keys).to include('evidence-submission-poll:123456')
end
it 'sets TTL to 60 seconds' do
subject.save
expect(subject.ttl).to be > 0
expect(subject.ttl).to be <= 60
end
it 'returns false for invalid record' do
invalid_record = described_class.new(claim_id: nil, request_ids: [111_111])
expect(invalid_record.save).to be false
end
end
describe '#update' do
it 'updates only the attributes passed in as arguments' do
subject.save
subject.update(request_ids: [999_999])
expect(subject.request_ids).to eq([999_999])
expect(subject.claim_id).to eq('123456')
end
end
describe '#destroy' do
it 'removes itself from redis' do
subject.save
expect(described_class).to exist('123456')
subject.destroy
expect(described_class).not_to exist('123456')
end
it 'freezes the instance after destroy is called' do
subject.save
subject.destroy
expect(subject.destroyed?).to be(true)
expect(subject.frozen?).to be(true)
end
end
describe '#persisted?' do
context 'when the record is not saved' do
it 'returns false' do
expect(subject).not_to be_persisted
end
end
context 'when the record is saved' do
it 'returns true' do
subject.save
expect(subject).to be_persisted
end
end
end
describe 'cache usage in controller context' do
it 'supports storing and retrieving sorted request_ids for comparison' do
# Simulate controller behavior: store unsorted array
described_class.create(claim_id: '999888', request_ids: [333_333, 111_111, 222_222])
# Retrieve and compare sorted arrays
cached = described_class.find('999888')
expect(cached.request_ids.sort).to eq([111_111, 222_222, 333_333])
end
it 'naturally expires after TTL' do
subject.save
expect(described_class.find('123456')).to be_present
# Fast-forward time simulation by checking TTL
expect(subject.ttl).to be > 0
expect(subject.ttl).to be <= 60
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/terms_of_use_agreement_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe TermsOfUseAgreement, type: :model do
let(:terms_of_use_agreement) do
build(:terms_of_use_agreement, user_account:, response:, agreement_version:)
end
let(:user_account) { create(:user_account) }
let(:response) { 'accepted' }
let(:agreement_version) { 'V1' }
describe 'default_scope' do
let!(:terms_of_use_agreement1) { create(:terms_of_use_agreement, created_at: 2.days.ago) }
let!(:terms_of_use_agreement2) { create(:terms_of_use_agreement, created_at: 1.day.ago) }
it 'orders by created_at ascending' do
expect(TermsOfUseAgreement.last).to eq(terms_of_use_agreement2)
end
end
describe 'associations' do
it 'belongs to a user_account' do
expect(terms_of_use_agreement.user_account).to eq(user_account)
end
end
describe 'validations' do
context 'when all attributes are valid' do
it 'is valid' do
expect(terms_of_use_agreement).to be_valid
end
end
context 'when response is missing' do
let(:response) { nil }
it 'is invalid' do
expect(terms_of_use_agreement).not_to be_valid
expect(terms_of_use_agreement.errors.attribute_names).to include(:response)
end
end
context 'when agreement_version is missing' do
let(:agreement_version) { nil }
it 'is invalid' do
expect(terms_of_use_agreement).not_to be_valid
expect(terms_of_use_agreement.errors.attribute_names).to include(:agreement_version)
end
end
describe 'response enum' do
context 'when response is accepted' do
let(:response) { 'accepted' }
it 'is valid' do
expect(terms_of_use_agreement).to be_valid
end
end
context 'when response is declined' do
let(:response) { 'declined' }
it 'is valid' do
expect(terms_of_use_agreement).to be_valid
end
end
context 'when response is not accepted or declined' do
it 'is invalid' do
expect do
terms_of_use_agreement.response = 'other_value'
end.to raise_error(ArgumentError, "'other_value' is not a valid response")
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/session_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Session, type: :model do
subject { described_class.new(attributes) }
let(:attributes) { { uuid: 'abcd-1234' } }
context 'session without attributes' do
it 'expect ttl to an Integer' do
expect(subject.ttl).to be_an(Integer)
expect(subject.ttl).to be_between(-Float::INFINITY, 0)
end
it 'assigns a token having length 40' do
expect(subject.token.length).to eq(40)
end
it 'assigns a created_at timestamp' do
expect(subject.created_at).to be_within(1.second).of(Time.now.utc)
end
it 'has a persisted attribute of false' do
expect(subject).not_to be_persisted
end
context 'with a matching user' do
let(:start_time) { Time.current.utc }
let(:expry_time) { start_time + 1800 }
let(:user) { create(:user, :mhv, uuid: attributes[:uuid]) }
before do
Timecop.freeze(start_time)
user
subject.save # persisting it to freeze the ttl
end
after do
Timecop.return
end
it '#ttl_in_time returns ttl of the session' do
expect(subject.ttl_in_time).to eq(expry_time)
end
end
end
describe 'redis persistence' do
before { subject.save }
context 'expire' do
it 'extends a session' do
expect(subject.expire(3600)).to be(true)
expect(subject.ttl).to eq(3600)
end
it 'extends the session when within maximum ttl' do
subject.created_at = subject.created_at - (described_class::MAX_SESSION_LIFETIME - 1.minute)
expect(subject.expire(1800)).to be(true)
end
it 'does not extend the session when beyond the maximum ttl' do
subject.created_at = subject.created_at - (described_class::MAX_SESSION_LIFETIME + 1.minute)
expect(subject.expire(1800)).to be(false)
expect(subject.errors.messages).to include(:created_at)
end
it 'allows for continuous session extension up to the maximum' do
start_time = Time.current
Timecop.freeze(start_time)
# keep extending session so Redis doesn't kill it while remaining
# within Sesion::MAX_SESSION_LIFETIME
increment = subject.redis_namespace_ttl - 60.seconds
max_hours = described_class::MAX_SESSION_LIFETIME / 1800.seconds
(1..max_hours).each do |hour|
Timecop.freeze(start_time + (increment * hour))
expect(subject.expire(described_class.redis_namespace_ttl)).to be(true)
expect(subject.ttl).to eq(described_class.redis_namespace_ttl)
end
# now outside Session::MAX_SESSION_LIFETIME
Timecop.freeze(start_time + (increment * max_hours) + increment)
expect(subject.expire(described_class.redis_namespace_ttl)).to be(false)
expect(subject.errors.messages).to include(:created_at)
Timecop.return
end
end
context 'save' do
it 'sets persisted flag to true' do
expect(subject).to be_persisted
end
it 'sets the ttl countdown' do
expect(subject.ttl).to be_an(Integer)
expect(subject.ttl).to be_between(0, 3600)
end
it 'saves a session within the maximum ttl' do
subject.created_at = subject.created_at - (described_class::MAX_SESSION_LIFETIME - 1.minute)
expect(subject.save).to be(true)
end
context 'when beyond the maximum ttl' do
before { subject.created_at = subject.created_at - (described_class::MAX_SESSION_LIFETIME + 1.minute) }
it 'does not save' do
expect(subject.save).to be(false)
expect(subject.errors.messages).to include(:created_at)
end
it 'logs info to Rails logger' do
expect(Rails.logger).to receive(:info).with(
'[Session] Maximum Session Duration Reached',
session_token: described_class.obscure_token(subject.token)
)
subject.save
end
end
end
context 'find' do
let(:found_session) { described_class.find(subject.token) }
it 'can find a saved session in redis' do
expect(found_session).to be_a(described_class)
expect(found_session.token).to eq(subject.token)
end
it 'expires and returns nil if session loaded from redis is invalid' do
allow_any_instance_of(described_class).to receive(:valid?).and_return(false)
expect(found_session).to be_nil
end
it 'returns nil if session was not found' do
expect(described_class.find('non-existent-token')).to be_nil
end
it 'does not change the created_at timestamp' do
orig_created_at = found_session.created_at
expect(found_session.save).to be(true)
expect(found_session.created_at).to eq(orig_created_at)
end
end
context 'destroy' do
it 'can destroy a session in redis' do
expect(subject.destroy).to eq(1)
expect(described_class.find(subject.token)).to be_nil
end
end
context 'authenticated_by_ssoe' do
let(:transaction_session) { described_class.new({ uuid: 'a', ssoe_transactionid: 'b' }) }
it 'is false when no transaction attribute is provided' do
expect(subject.authenticated_by_ssoe).to be_falsey
end
it 'is true when a transaction attribute is provided' do
expect(transaction_session.authenticated_by_ssoe).to be_truthy
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/nod_notification_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe NodNotification, type: :model do
let(:nod_notification) { build(:nod_notification) }
describe 'payload encryption' do
it 'encrypts the payload field' do
expect(subject).to encrypt_attr(:payload)
end
end
describe 'validations' do
it 'validates presence of payload' do
expect_attr_valid(nod_notification, :payload)
nod_notification.payload = nil
expect_attr_invalid(nod_notification, :payload, "can't be blank")
end
end
describe '#serialize_payload' do
let(:payload) do
{ a: 1 }
end
it 'serializes payload as json' do
nod_notification.payload = payload
nod_notification.save!
expect(nod_notification.payload).to eq(payload.to_json)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/saml_request_tracker_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SAMLRequestTracker, type: :model do
describe '#save' do
context 'with a datetime of 2020-01-01T08:00:00Z' do
before { Timecop.freeze(Time.zone.parse('2020-01-01T08:00:00Z')) }
after { Timecop.return }
it 'sets created_at when missing' do
tracker = SAMLRequestTracker.create(uuid: 1, payload: {})
expect(tracker.created_at).to eq(1_577_865_600)
end
end
it 'leaves created_at untouched when already set' do
tracker = SAMLRequestTracker.create(uuid: 1, payload: {}, created_at: 10)
expect(tracker.created_at).to eq(10)
end
it 'sets payload when missing' do
tracker = SAMLRequestTracker.create(uuid: 1)
expect(tracker.payload).to eq({})
end
end
describe '#payload_attr' do
it 'nil when not found' do
tracker = SAMLRequestTracker.new
expect(tracker.payload_attr(:x)).to be_nil
end
it 'nil when attribute is missing' do
tracker = SAMLRequestTracker.new(payload: {})
expect(tracker.payload_attr(:x)).to be_nil
end
it 'finds payload attribute' do
tracker = SAMLRequestTracker.new(payload: { x: 'ok' })
expect(tracker.payload_attr(:x)).to eq('ok')
end
end
describe '#age' do
context 'when age is not set' do
it 'returns 0' do
tracker = SAMLRequestTracker.new
expect(tracker.age).to eq(0)
end
end
context 'when age is set' do
before { Timecop.freeze(Time.zone.parse('2020-01-01T08:00:00Z')) }
after { Timecop.return }
it 'returns the set age' do
tracker = SAMLRequestTracker.create(uuid: 1, payload: {})
Timecop.freeze(Time.zone.parse('2020-01-01T08:03:00Z'))
expect(tracker.age).to eq(180)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/tracking_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe Tracking do
let(:tracking_attributes) { attributes_for(:tracking) }
context 'with valid attributes' do
subject { described_class.new(tracking_attributes) }
it 'has attributes' do
expect(subject).to have_attributes(prescription_name: 'Drug 1 250MG TAB', prescription_number: '2719324',
facility_name: 'ABC123', rx_info_phone_number: '(333)772-1111',
ndc_number: '12345678910', delivery_service: 'UPS',
tracking_number: '01234567890')
end
it 'has date attribute' do
expect(subject).to have_attributes(shipped_date: Time.parse('Thu, 12 Oct 2016 00:00:00 EDT').in_time_zone)
end
end
context 'additional attribute for prescription_id' do
let(:tracking_with_prescription_id) { described_class.new(attributes_for(:tracking, prescription_id: '1')) }
it 'assigns prescription id' do
expect(tracking_with_prescription_id.prescription_id).to eq(1)
end
context 'it sorts' do
subject { [t1, t2, t3, t4] }
let(:t1) { tracking_with_prescription_id }
let(:t2) { tracking_with_prescription_id }
let(:t3) { described_class.new(attributes_for(:tracking, prescription_id: '2', shipped_date: Time.now.utc)) }
let(:t4) { described_class.new(attributes_for(:tracking, :oldest, prescription_id: '3')) }
it 'sorts by shipped_date by default' do
expect(subject.sort.map(&:prescription_id))
.to eq([2, 1, 1, 3])
end
it 'sorts by sort_by field' do
expect(subject.sort_by(&:prescription_id).map(&:prescription_id))
.to eq([1, 1, 2, 3])
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_relationship_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserRelationship, type: :model do
describe '.from_bgs_dependent' do
let(:user_relationship) { described_class.from_bgs_dependent(bgs_dependent) }
let(:bgs_dependent) do
{
award_indicator: 'N',
city_of_birth: 'WASHINGTON',
current_relate_status: '',
date_of_birth: '01/01/2000',
date_of_death: '',
death_reason: '',
email_address: 'Curt@email.com',
first_name: 'CURT',
gender: '',
last_name: 'WEBB-STER',
middle_name: '',
proof_of_dependency: 'Y',
ptcpnt_id: '32354974',
related_to_vet: 'N',
relationship: 'Child',
ssn: '500223351',
ssn_verify_status: '1',
state_of_birth: 'DC'
}
end
it 'creates a UserRelationship object with attributes from a BGS Dependent call' do
expect(user_relationship.first_name).to eq bgs_dependent[:first_name]
expect(user_relationship.last_name).to eq bgs_dependent[:last_name]
expect(user_relationship.birth_date).to eq Formatters::DateFormatter.format_date(bgs_dependent[:date_of_birth])
expect(user_relationship.ssn).to eq bgs_dependent[:ssn]
expect(user_relationship.gender).to eq bgs_dependent[:gender]
expect(user_relationship.veteran_status).to be false
expect(user_relationship.participant_id).to eq bgs_dependent[:ptcpnt_id]
end
end
describe '.from_mpi_relationship' do
let(:mpi_relationship) { build(:mpi_profile_relationship) }
let(:user_relationship) { described_class.from_mpi_relationship(mpi_relationship) }
it 'creates a UserRelationship object with attributes from an MPI Profile RelationshipHolder stanza' do
expect(user_relationship.first_name).to eq mpi_relationship.given_names.first
expect(user_relationship.last_name).to eq mpi_relationship.family_name
expect(user_relationship.birth_date).to eq Formatters::DateFormatter.format_date(mpi_relationship.birth_date)
expect(user_relationship.ssn).to eq mpi_relationship.ssn
expect(user_relationship.gender).to eq mpi_relationship.gender
expect(user_relationship.veteran_status).to eq mpi_relationship.person_types.include? 'VET'
expect(user_relationship.icn).to eq mpi_relationship.icn
expect(user_relationship.participant_id).to eq mpi_relationship.participant_id
end
end
describe '#to_hash' do
let(:mpi_relationship) { build(:mpi_profile_relationship) }
let(:user_relationship) { described_class.from_mpi_relationship(mpi_relationship) }
let(:user_relationship_hash) do
{
first_name: mpi_relationship.given_names.first,
last_name: mpi_relationship.family_name,
birth_date: Formatters::DateFormatter.format_date(mpi_relationship.birth_date)
}
end
it 'creates a spare hash of select attributes for frontend serialization' do
expect(user_relationship.to_hash).to eq user_relationship_hash
end
end
describe '#get_full_attributes' do
let(:mpi_relationship) { build(:mpi_profile_relationship) }
let(:user_relationship) { described_class.from_mpi_relationship(mpi_relationship) }
let(:mpi_object_double) { double }
before do
allow(MPIData).to receive(:for_user).and_return(mpi_object_double)
end
it 'returns an MPI profile for relationship attributes' do
expect(user_relationship.get_full_attributes).to eq mpi_object_double
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/accredited_organization_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe AccreditedOrganization, type: :model do
describe 'validations' do
subject { build(:accredited_organization, poa_code: 'A12') }
it { is_expected.to have_many(:accredited_individuals).through(:accreditations) }
it { expect(subject).to validate_presence_of(:ogc_id) }
it { expect(subject).to validate_presence_of(:poa_code) }
it { expect(subject).to validate_length_of(:poa_code).is_equal_to(3) }
it { expect(subject).to validate_uniqueness_of(:poa_code) }
end
describe '.find_within_max_distance' do
# ~6 miles from Washington, D.C.
let!(:ai1) do
create(:accredited_organization, poa_code: '123', long: -77.050552, lat: 38.820450,
location: 'POINT(-77.050552 38.820450)')
end
# ~35 miles from Washington, D.C.
let!(:ai2) do
create(:accredited_organization, poa_code: '234', long: -76.609383, lat: 39.299236,
location: 'POINT(-76.609383 39.299236)')
end
# ~47 miles from Washington, D.C.
let!(:ai3) do
create(:accredited_organization, poa_code: '345', long: -77.466316, lat: 38.309875,
location: 'POINT(-77.466316 38.309875)')
end
# ~57 miles from Washington, D.C.
let!(:ai4) do
create(:accredited_organization, poa_code: '456', long: -76.3483, lat: 39.5359,
location: 'POINT(-76.3483 39.5359)')
end
context 'when there are organizations within the max search distance' do
it 'returns all organizations located within the default max distance' do
# check within 50 miles of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072)
expect(results.pluck(:id)).to contain_exactly(ai1.id, ai2.id, ai3.id)
end
it 'returns all organizations located within the specified max distance' do
# check within 40 miles of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072, 64_373.8)
expect(results.pluck(:id)).to contain_exactly(ai1.id, ai2.id)
end
end
context 'when there are no organizations within the max search distance' do
it 'returns an empty array' do
# check within 1 mile of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072, 1609.344)
expect(results).to eq([])
end
end
end
describe '#registration_numbers' do
let(:organization) { create(:accredited_organization) }
context 'when the organization has no accredited_individual associations' do
it 'returns an empty array' do
expect(organization.registration_numbers).to eq([])
end
end
context 'when the organization has accredited_individual associations' do
let(:ind1) { create(:accredited_individual, registration_number: '12300') }
let(:ind2) { create(:accredited_individual, registration_number: '45600') }
it 'returns an array of all associated registration_numbers' do
organization.accredited_individuals.push(ind1, ind2)
expect(organization.reload.registration_numbers).to match_array(%w[12300 45600])
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/intent_to_file_queue_exhaustion_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe IntentToFileQueueExhaustion, type: :model do
describe 'validations' do
it { is_expected.to validate_presence_of(:veteran_icn) }
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/deprecated_user_account_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DeprecatedUserAccount, type: :model do
let(:deprecated_user_account) do
create(:deprecated_user_account, user_verification:, user_account:)
end
let(:user_verification) { create(:user_verification) }
let(:user_account) { create(:user_account) }
describe 'validations' do
describe '#user_account' do
subject { deprecated_user_account.user_account }
context 'when user_account is nil' do
let(:user_account) { nil }
let(:expected_error_message) { 'Validation failed: User account must exist' }
it 'raises a validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
context 'when user_account is not nil' do
let(:user_account) { create(:user_account) }
it 'returns given user_account' do
expect(subject).to eq(user_account)
end
end
end
describe '#user_verification' do
subject { deprecated_user_account.user_verification }
context 'when user_verification is nil' do
let(:user_verification) { nil }
let(:expected_error_message) do
'Validation failed: User verification must exist'
end
it 'raises a validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
context 'when user_verification is not nil' do
let(:user_verification) { create(:user_verification) }
it 'returns given user_verification' do
expect(subject).to eq(user_verification)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/application_record_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ApplicationRecord do
it 'ensures all encrypted models have the needs_kms_rotation column' do
encrypted_models = ApplicationRecord.descendants_using_encryption
missing = encrypted_models.reject { |model| model.column_names.include?('needs_kms_rotation') }
expect(missing).to be_empty, lambda {
<<~MSG
The following models use encryption but are missing the `needs_kms_rotation` column:
#{missing.map(&:name).join("\n")}
MSG
}
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/education_stem_automated_decision_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EducationStemAutomatedDecision, type: :model do
subject { described_class.new }
describe 'auth_headers' do
it 'returns nil without saved auth_headers' do
expect(subject.auth_headers).to be_nil
end
it 'correctly returns hash' do
user = create(:user, :loa3, :with_terms_of_use_agreement)
subject.education_benefits_claim = create(:education_benefits_claim)
subject.auth_headers_json = EVSS::AuthHeaders.new(user).to_h.to_json
subject.user_account = user.user_account
expect(subject.auth_headers).not_to be_nil
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/category_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Category do
subject { described_class.new(params) }
let(:params) { attributes_for(:category) }
it 'populates attributes' do
expect(subject.message_category_type).to eq(params[:message_category_type])
end
it 'can be compared but always equal' do
expect(subject <=> build(:category)).to eq(0)
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/secondary_appeal_form_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SecondaryAppealForm, type: :model do
subject { build(:secondary_appeal_form4142) }
describe 'validations' do
before do
expect(subject).to be_valid
end
it { is_expected.to validate_presence_of(:guid) }
it { is_expected.to validate_presence_of(:form_id) }
it { is_expected.to validate_presence_of(:form) }
end
describe 'incomplete scope' do
let(:complete_form) { create(:secondary_appeal_form4142, delete_date: 10.days.ago) }
let(:incomplete_form) { create(:secondary_appeal_form4142) }
it 'only returns records without a delete_date' do
results = SecondaryAppealForm.incomplete
expect(results).to contain_exactly(incomplete_form)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/all_triage_teams_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe AllTriageTeams, type: :model do
subject { described_class.new }
describe 'attributes' do
it 'has the expected attributes' do
expect(subject.attributes.keys).to include(
'triage_team_id',
'name',
'station_number',
'blocked_status',
'preferred_team',
'relation_type',
'lead_provider_name',
'location_name',
'team_name',
'suggested_name_display',
'health_care_system_name',
'group_type_enum_val',
'sub_group_type_enum_val',
'group_type_patient_display',
'sub_group_type_patient_display',
'oh_triage_group'
)
end
it 'has default values for boolean attributes' do
expect(subject.blocked_status).to be false
expect(subject.preferred_team).to be false
end
end
describe 'sorting' do
it 'has default sort configured' do
# The model has default_sort_by name: :asc configured
expect(described_class.instance_variable_get(:@default_sort_criteria)).to eq(name: :asc)
end
end
describe 'vets model' do
it 'includes Vets::Model module' do
expect(described_class.included_modules).to include(Vets::Model)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/personal_information_log_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe PersonalInformationLog, type: :model do
let(:personal_information_log) { build(:personal_information_log) }
describe 'validations' do
context 'when all attributes are valid' do
it 'is valid' do
expect(personal_information_log).to be_valid
end
end
context 'when error class is missing' do
it 'is invalid' do
personal_information_log.error_class = nil
expect(personal_information_log).not_to be_valid
expect(personal_information_log.errors.attribute_names).to include(:error_class)
expect(personal_information_log.errors.full_messages).to include("Error class can't be blank")
end
end
end
describe '#data' do
context 'when data is missing' do
let(:pi_log) { build(:personal_information_log, data: nil) }
it 'does not raise error' do
expect { pi_log.save }.not_to raise_error
end
end
context 'when all attributes are present' do
it 'simply returns data' do
expect(personal_information_log.data).to eq({ 'foo' => 1 })
end
it 'populates the data_ciphertext' do
expect(personal_information_log.data_ciphertext).to be_present
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/mhv_user_account_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe MHVUserAccount, type: :model do
subject(:mhv_user_account) { described_class.new(attributes) }
let(:attributes) do
{
user_profile_id:,
premium:,
champ_va:,
patient:,
sm_account_created:,
message:
}
end
let(:user_profile_id) { '123' }
let(:premium) { true }
let(:champ_va) { true }
let(:patient) { false }
let(:sm_account_created) { true }
let(:message) { 'some-message' }
context 'with valid attributes' do
shared_examples 'a valid user account' do
it 'is valid' do
expect(mhv_user_account).to be_valid
end
end
context 'when all attributes are present' do
it 'is valid' do
expect(mhv_user_account).to be_valid
end
end
context 'when message is nil' do
let(:message) { nil }
it_behaves_like 'a valid user account'
end
end
context 'with invalid attributes' do
shared_examples 'an invalid user account' do
it 'is invalid' do
expect(mhv_user_account).not_to be_valid
end
end
context 'when user_profile_id is nil' do
let(:user_profile_id) { nil }
it_behaves_like 'an invalid user account'
end
context 'when premium is nil' do
let(:premium) { nil }
it_behaves_like 'an invalid user account'
end
context 'when champ_va is nil' do
let(:champ_va) { nil }
it_behaves_like 'an invalid user account'
end
context 'when patient is nil' do
let(:patient) { nil }
it_behaves_like 'an invalid user account'
end
context 'when sm_account_created is nil' do
let(:sm_account_created) { nil }
it_behaves_like 'an invalid user account'
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form_profile_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'decision_review/schemas'
require 'disability_compensation/factories/api_provider_factory'
require 'gi/client'
RSpec.describe FormProfile, type: :model do
include SchemaMatchers
before do
allow(Flipper).to receive(:enabled?).and_call_original
allow(Flipper).to receive(:enabled?).with(:dependents_module_enabled, anything).and_return(false)
allow(Flipper).to receive(:enabled?).with(:disability_526_max_cfi_service_switch, anything).and_return(false)
described_class.instance_variable_set(:@mappings, nil)
end
let(:user) do
build(:user, :loa3, :legacy_icn, idme_uuid: 'b2fab2b5-6af0-45e1-a9e2-394347af91ef', suffix: 'Jr.',
address: build(:va_profile_address), vet360_id: '1')
end
let(:contact_info) { form_profile.send :initialize_contact_information }
let(:form_profile) do
described_class.new(form_id: 'foo', user:)
end
let(:va_profile_address) { contact_info&.address }
let(:us_phone) { contact_info&.home_phone }
let(:mobile_phone) { contact_info&.mobile_phone }
let(:full_name) do
{
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
}
end
let(:veteran_service_information) do
{
'branchOfService' => 'Army',
'serviceDateRange' => {
'from' => '2012-03-02',
'to' => '2018-10-31'
}
}
end
let(:veteran_full_name) do
{
'veteranFullName' => full_name
}
end
let(:address) do
{
'street' => va_profile_address.street,
'street2' => va_profile_address.street2,
'city' => va_profile_address.city,
'state' => va_profile_address.state,
'country' => va_profile_address.country,
'postal_code' => va_profile_address.postal_code
}
end
let(:veteran_address) do
{
'veteranAddress' => address
}
end
let(:tours_of_duty) do
[
{
'service_branch' => 'Army',
'date_range' => { 'from' => '1985-08-19', 'to' => '1989-08-19' }
},
{
'service_branch' => 'Army',
'date_range' => { 'from' => '1989-08-20', 'to' => '1992-08-23' }
},
{
'service_branch' => 'Army',
'date_range' => { 'from' => '1989-08-20', 'to' => '2002-07-01' }
},
{
'service_branch' => 'Air Force',
'date_range' => { 'from' => '2000-04-07', 'to' => '2009-01-23' }
},
{
'service_branch' => 'Army',
'date_range' => { 'from' => '2002-07-02', 'to' => '2014-08-31' }
}
]
end
let(:v40_10007_expected) do
{
'application' => {
'claimant' => {
'address' => address,
'dateOfBirth' => user.birth_date,
'name' => full_name,
'ssn' => user.ssn,
'email' => user.va_profile_email,
'phoneNumber' => us_phone
}
}
}
end
let(:v0873_expected) do
user_work_phone = user.vet360_contact_info.work_phone
work_phone = [
user_work_phone.country_code,
user_work_phone.area_code,
user_work_phone.phone_number,
user_work_phone.extension
].compact.join
{
'personalInformation' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix,
'preferredName' => 'SAM',
'dateOfBirth' => user.birth_date,
'socialSecurityNumber' => user.ssn,
'serviceNumber' => '123455678'
},
'contactInformation' => {
'email' => user.va_profile_email,
'phone' => us_phone,
'address' => address,
'workPhone' => work_phone
},
'avaProfile' => {
'schoolInfo' => {
'schoolFacilityCode' => '12345678',
'schoolName' => 'Fake School'
},
'businessPhone' => '1234567890',
'businessEmail' => 'fake@company.com'
},
'veteranServiceInformation' => veteran_service_information
}
end
let(:v686_c_674_expected) do
{
'veteranContactInformation' => {
'veteranAddress' => {
'addressLine1' => '140 Rock Creek Rd',
'countryName' => 'USA',
'city' => 'Washington',
'stateCode' => 'DC',
'zipCode' => '20011'
},
'phoneNumber' => '3035551234',
'emailAddress' => user.va_profile_email
},
'nonPrefill' => {
'veteranSsnLastFour' => '1863',
'veteranVaFileNumberLastFour' => '1863'
},
'veteranInformation' => {
'fullName' => {
'first' => user.first_name.capitalize,
'last' => user.last_name.capitalize,
'suffix' => 'Jr.'
},
'ssn' => '796111863',
'birthDate' => '1809-02-12'
}
}
end
let(:v686_c_674_v2_expected) do
{
'veteranContactInformation' => {
'veteranAddress' => {
'street' => '140 Rock Creek Rd',
'country' => 'USA',
'city' => 'Washington',
'state' => 'DC',
'postalCode' => '20011'
},
'phoneNumber' => us_phone,
'emailAddress' => user.va_profile_email
},
'nonPrefill' => {
'veteranSsnLastFour' => '1863',
'veteranVaFileNumberLastFour' => '1863',
'isInReceiptOfPension' => -1,
'netWorthLimit' => 163_699
},
'veteranInformation' => {
'fullName' => {
'first' => user.first_name.capitalize,
'last' => user.last_name.capitalize
},
'ssn' => '796111863',
'birthDate' => '1809-02-12'
}
}
end
let(:v21_686_c_expected) do
{
'veteranFullName' => {
'first' => 'WESLEY',
'middle' => 'Watson',
'last' => 'FORD'
},
'veteranAddress' => {
'addressType' => 'DOMESTIC',
'street' => '3001 PARK CENTER DR',
'street2' => 'APT 212',
'city' => 'ALEXANDRIA',
'state' => 'VA',
'countryDropdown' => 'USA',
'postalCode' => '22302'
},
'veteranEmail' => 'evssvsotest@gmail.com',
'veteranSocialSecurityNumber' => '796043735',
'dayPhone' => '2024619724',
'maritalStatus' => 'NEVERMARRIED',
'nightPhone' => '7893256545',
'spouseMarriages' => [
{
'dateOfMarriage' => '1979-02-01',
'locationOfMarriage' => {
'countryDropdown' => 'USA',
'city' => 'Washington',
'state' => 'DC'
},
'spouseFullName' => {
'first' => 'Dennis',
'last' => 'Menise'
}
}
],
'marriages' => [
{
'dateOfMarriage' => '1979-02-01',
'locationOfMarriage' => {
'countryDropdown' => 'USA',
'city' => 'Washington',
'state' => 'DC'
},
'spouseFullName' => {
'first' => 'Dennis',
'last' => 'Menise'
}
},
{
'dateOfMarriage' => '2018-02-02',
'locationOfMarriage' => {
'countryDropdown' => 'USA',
'city' => 'Washington',
'state' => 'DC'
},
'spouseFullName' => {
'first' => 'Martha',
'last' => 'Stewart'
}
}
],
'currentMarriage' => {
'spouseSocialSecurityNumber' => '579009999',
'liveWithSpouse' => true,
'spouseDateOfBirth' => '1969-02-16'
},
'dependents' => [
{
'fullName' => {
'first' => 'ONE',
'last' => 'FORD'
},
'childDateOfBirth' => '2018-08-02',
'childInHousehold' => true,
'childHasNoSsn' => true,
'childHasNoSsnReason' => 'NOSSNASSIGNEDBYSSA'
},
{
'fullName' => {
'first' => 'TWO',
'last' => 'FORD'
},
'childDateOfBirth' => '2018-08-02',
'childInHousehold' => true,
'childSocialSecurityNumber' => '092120182'
},
{
'fullName' => {
'first' => 'THREE',
'last' => 'FORD'
},
'childDateOfBirth' => '2017-08-02',
'childInHousehold' => true,
'childSocialSecurityNumber' => '092120183'
},
{
'fullName' => {
'first' => 'FOUR',
'last' => 'FORD'
},
'childDateOfBirth' => '2017-08-02',
'childInHousehold' => true,
'childSocialSecurityNumber' => '092120184'
},
{
'fullName' => {
'first' => 'FIVE',
'last' => 'FORD'
},
'childDateOfBirth' => '2016-08-02',
'childInHousehold' => true,
'childSocialSecurityNumber' => '092120185'
},
{
'fullName' => {
'first' => 'SIX',
'last' => 'FORD'
},
'childDateOfBirth' => '2015-08-02',
'childInHousehold' => true,
'childSocialSecurityNumber' => '092120186'
},
{
'fullName' => {
'first' => 'TEST',
'last' => 'FORD'
},
'childDateOfBirth' => '2018-08-07',
'childInHousehold' => true,
'childSocialSecurityNumber' => '221223524'
}
]
}
end
let(:v22_1990_expected) do
{
'toursOfDuty' => tours_of_duty,
'currentlyActiveDuty' => {
'yes' => false
},
'veteranAddress' => address,
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'gender' => user.gender,
'homePhone' => us_phone,
'mobilePhone' => mobile_phone,
'veteranDateOfBirth' => user.birth_date,
'veteranSocialSecurityNumber' => user.ssn,
'email' => user.va_profile_email
}
end
let(:v22_0993_expected) do
{
'claimantFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'claimantSocialSecurityNumber' => user.ssn
}
end
let(:v22_0994_expected) do
{
'activeDuty' => false,
'mailingAddress' => address,
'applicantFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'applicantGender' => user.gender,
'dayTimePhone' => us_phone,
'nightTimePhone' => mobile_phone,
'dateOfBirth' => user.birth_date,
'applicantSocialSecurityNumber' => user.ssn,
'emailAddress' => user.va_profile_email
}
end
let(:v22_1990_n_expected) do
{
'toursOfDuty' => tours_of_duty,
'currentlyActiveDuty' => {
'yes' => false
},
'veteranAddress' => address,
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'gender' => user.gender,
'homePhone' => us_phone,
'veteranDateOfBirth' => user.birth_date,
'veteranSocialSecurityNumber' => user.ssn,
'email' => user.va_profile_email
}
end
let(:v22_1990_e_expected) do
{
'relativeAddress' => address,
'relativeFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'relativeSocialSecurityNumber' => user.ssn
}
end
let(:v22_1995_expected) do
{
'veteranAddress' => address,
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'homePhone' => us_phone,
'veteranSocialSecurityNumber' => user.ssn,
'email' => user.va_profile_email
}
end
let(:v22_1995_s_expected) do
{
'veteranAddress' => address,
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'homePhone' => us_phone,
'veteranSocialSecurityNumber' => user.ssn,
'email' => user.va_profile_email
}
end
let(:v22_10203_expected) do
{
'veteranAddress' => address,
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'homePhone' => us_phone,
'mobilePhone' => mobile_phone,
'veteranSocialSecurityNumber' => user.ssn,
'email' => user.va_profile_email
}
end
let(:v22_5490_expected) do
{
'toursOfDuty' => tours_of_duty,
'currentlyActiveDuty' => false,
'relativeFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'relativeSocialSecurityNumber' => user.ssn,
'relativeDateOfBirth' => user.birth_date
}
end
let(:v22_5495_expected) do
{
'toursOfDuty' => tours_of_duty,
'currentlyActiveDuty' => false,
'relativeFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'relativeSocialSecurityNumber' => user.ssn,
'relativeDateOfBirth' => user.birth_date
}
end
let(:v1010ez_expected) do
{
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'veteranDateOfBirth' => user.birth_date,
'email' => user.va_profile_email,
'veteranAddress' => address,
'swAsiaCombat' => false,
'lastServiceBranch' => 'army',
'lastEntryDate' => '2002-07-02',
'lastDischargeDate' => '2014-08-31',
'gender' => user.gender,
'homePhone' => us_phone,
'veteranSocialSecurityNumber' => user.ssn
}
end
let(:vmdot_expected) do
{
'fullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'permanentAddress' => {
'street' => '456 ANYPLACE RD',
'city' => 'PENSACOLA',
'state' => 'FL',
'country' => 'United States',
'postalCode' => '33344'
},
'temporaryAddress' => {
'street' => '123 SOMEWHERE',
'street2' => 'OUT THERE',
'city' => 'DENVER',
'state' => 'CO',
'country' => 'United States',
'postalCode' => '80030'
},
'ssnLastFour' => user.ssn.last(4),
'gender' => user.gender,
'vetEmail' => 'veteran@gmail.com',
'dateOfBirth' => user.birth_date,
'eligibility' => {
'accessories' => true,
'apneas' => true,
'batteries' => true
},
'supplies' => [
{
'productName' => 'ERHK HE11 680 MINI',
'productGroup' => 'ACCESSORIES',
'productId' => 6584,
'availableForReorder' => true,
'lastOrderDate' => '2019-11-22',
'nextAvailabilityDate' => '2020-04-22',
'quantity' => 1
},
{
'productName' => 'ZA10',
'productGroup' => 'BATTERIES',
'productId' => 3315,
'availableForReorder' => true,
'lastOrderDate' => '2019-12-01',
'nextAvailabilityDate' => '2020-05-01',
'quantity' => 24
},
{
'deviceName' => 'WILLIAMS SOUND CORP./POCKETALKER II',
'productName' => 'M312',
'productGroup' => 'BATTERIES',
'productId' => 2298,
'availableForReorder' => false,
'lastOrderDate' => '2020-05-06',
'nextAvailabilityDate' => '2020-10-06',
'quantity' => 12
},
{
'deviceName' => 'SIVANTOS/SIEMENS/007ASP2',
'productName' => 'ZA13',
'productGroup' => 'BATTERIES',
'productId' => 2314,
'availableForReorder' => false,
'lastOrderDate' => '2020-05-06',
'nextAvailabilityDate' => '2020-10-06',
'quantity' => 60
},
{
'deviceName' => '',
'productName' => 'AIRFIT P10',
'productGroup' => 'Apnea',
'productId' => 6650,
'availableForReorder' => true,
'lastOrderDate' => '2022-07-05',
'nextAvailabilityDate' => '2022-12-05',
'quantity' => 1
},
{
'deviceName' => '',
'productName' => 'AIRCURVE10-ASV-CLIMATELINE',
'productGroup' => 'Apnea',
'productId' => 8467,
'availableForReorder' => false,
'lastOrderDate' => '2022-07-06',
'nextAvailabilityDate' => '2022-12-06',
'quantity' => 1
}
]
}
end
let(:v5655_expected) do
{
'personalIdentification' => {
'ssn' => user.ssn.last(4),
'fileNumber' => '3735'
},
'personalData' => {
'veteranFullName' => full_name,
'address' => address,
'telephoneNumber' => us_phone,
'emailAddress' => user.va_profile_email,
'dateOfBirth' => user.birth_date
},
'income' => [
{
'veteranOrSpouse' => 'VETERAN',
'compensationAndPension' => '3000'
}
]
}
end
let(:vvic_expected) do
{
'email' => user.va_profile_email,
'serviceBranches' => ['F'],
'gender' => user.gender,
'verified' => true,
'veteranDateOfBirth' => user.birth_date,
'phone' => us_phone,
'veteranSocialSecurityNumber' => user.ssn
}.merge(veteran_full_name).merge(veteran_address)
end
let(:v21_p_527_ez_expected) do
{
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'veteranAddress' => address,
'email' => user.va_profile_email,
'phone' => us_phone,
'mobilePhone' => mobile_phone,
'internationalPhone' => '3035551234',
'serviceBranch' => {
'army' => true,
'airForce' => true
},
'activeServiceDateRange' => {
'from' => '1984-08-01',
'to' => '2014-08-31'
},
'serviceNumber' => '796111863',
'veteranSocialSecurityNumber' => user.ssn,
'veteranDateOfBirth' => user.birth_date
}
end
let(:v21_p_530_ez_expected) do
{
'claimantFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'claimantAddress' => address,
'claimantPhone' => us_phone,
'claimantEmail' => user.va_profile_email
}
end
let(:v21_526_ez_expected) do
{
'disabilities' => [
{
'diagnosticCode' => 5238,
'decisionCode' => 'SVCCONNCTED',
'decisionText' => 'Service Connected',
'name' => 'Diabetes mellitus0',
'ratedDisabilityId' => '1',
'ratingDecisionId' => '0',
'ratingPercentage' => 50
}
],
'servicePeriods' => [
{
'serviceBranch' => 'Army',
'dateRange' => { 'from' => '2002-07-02', 'to' => '2014-08-31' }
},
{
'serviceBranch' => 'Air National Guard',
'dateRange' => { 'from' => '2000-04-07', 'to' => '2009-01-23' }
},
{
'serviceBranch' => 'Army Reserve',
'dateRange' => { 'from' => '1989-08-20', 'to' => '2002-07-01' }
},
{
'serviceBranch' => 'Army Reserve',
'dateRange' => { 'from' => '1989-08-20', 'to' => '1992-08-23' }
},
{
'serviceBranch' => 'Army',
'dateRange' => { 'from' => '1985-08-19', 'to' => '1989-08-19' }
}
],
'reservesNationalGuardService' => {
'obligationTermOfServiceDateRange' => {
'from' => '2000-04-07',
'to' => '2009-01-23'
}
},
'veteran' => {
'mailingAddress' => {
'country' => 'USA',
'city' => 'Washington',
'state' => 'DC',
'zipCode' => '20011',
'addressLine1' => '140 Rock Creek Rd'
},
'primaryPhone' => '3035551234',
'emailAddress' => 'person101@example.com'
},
'bankAccountNumber' => '******7890',
'bankAccountType' => 'Checking',
'bankName' => 'WELLS FARGO BANK',
'bankRoutingNumber' => '*****0503',
'startedFormVersion' => '2022',
'syncModern0781Flow' => true
}
end
let(:vfeedback_tool_expected) do
{
'address' => {
'street' => va_profile_address.street,
'street2' => va_profile_address.street2,
'city' => va_profile_address.city,
'state' => va_profile_address.state,
'country' => 'US',
'postal_code' => va_profile_address.postal_code
},
'serviceBranch' => 'Army',
'fullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'applicantEmail' => user.va_profile_email,
'phone' => us_phone,
'serviceDateRange' => {
'from' => '2002-07-02',
'to' => '2014-08-31'
}
}
end
let(:v21_2680_expected) do
{ veteranInformation: {
veteranFullName: {
first: 'Abraham',
last: 'Lincoln',
suffix: 'Jr.'
},
veteranDob: '1809-02-12',
phoneNumber: '3035551234',
email: user.va_profile_email,
veteranAddress: {
street: '140 Rock Creek Rd',
city: 'Washington',
state: 'DC',
country: 'USA',
postalCode: '20011'
},
veteranSsn: '796111863'
} }
end
let(:v26_1880_expected) do
{
'fullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'dateOfBirth' => '1809-02-12',
'applicantAddress' => address,
'contactPhone' => us_phone,
'contactEmail' => user.va_profile_email,
'periodsOfService' => tours_of_duty,
'currentlyActiveDuty' => {
'yes' => false
},
'activeDuty' => false
}
end
let(:v28_8832_expected) do
{
'claimantAddress' => address,
'claimantPhoneNumber' => us_phone,
'claimantEmailAddress' => user.va_profile_email
}
end
let(:vform_mock_ae_design_patterns_expected) do
{
'data' => {
'attributes' => {
'veteran' => {
'firstName' => user.first_name&.capitalize,
'middleName' => user.middle_name&.capitalize,
'lastName' => user.last_name&.capitalize,
'suffix' => user.suffix,
'dateOfBirth' => user.birth_date,
'ssn' => user.ssn.last(4),
'gender' => user.gender,
'address' => {
'addressLine1' => va_profile_address.street,
'addressLine2' => va_profile_address.street2,
'city' => va_profile_address.city,
'stateCode' => va_profile_address.state,
'countryName' => va_profile_address.country,
'zipCode5' => va_profile_address.postal_code
},
'phone' => {
'areaCode' => us_phone[0..2],
'phoneNumber' => us_phone[3..9]
},
'homePhone' => '3035551234',
'mobilePhone' => mobile_phone,
'emailAddressText' => user.va_profile_email,
'lastServiceBranch' => 'Army'
}
}
}
}
end
let(:v28_1900_expected) do
{
'veteranInformation' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '796111863',
'dob' => '1809-02-12'
},
'veteranAddress' => address,
'mainPhone' => us_phone,
'email' => user.va_profile_email,
'cellPhone' => mobile_phone
}
end
let(:v21_22_expected) do
{
'personalInformation' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '796111863',
'dateOfBirth' => '1809-02-12'
},
'contactInformation' => {
'email' => user.va_profile_email,
'address' => address,
'primaryPhone' => '3035551234'
},
'militaryInformation' => {
'serviceBranch' => 'Army',
'serviceDateRange' => {
'from' => '2002-07-02',
'to' => '2014-08-31'
}
},
'identityValidation' => {
'hasICN' => true,
'hasParticipantId' => true,
'isLoa3' => true
}
}
end
let(:v21_22_a_expected) do
{
'personalInformation' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '796111863',
'dateOfBirth' => '1809-02-12'
},
'contactInformation' => {
'email' => user.va_profile_email,
'address' => address,
'primaryPhone' => '3035551234'
},
'militaryInformation' => {
'serviceBranch' => 'Army',
'serviceDateRange' => {
'from' => '2002-07-02',
'to' => '2014-08-31'
}
},
'identityValidation' => {
'hasICN' => true,
'hasParticipantId' => true,
'isLoa3' => true
}
}
end
let(:v26_4555_expected) do
{
'veteran' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '796111863',
'dateOfBirth' => '1809-02-12',
'homePhone' => us_phone,
'mobilePhone' => mobile_phone,
'email' => user.va_profile_email,
'address' => address
}
}
end
let(:v21_0966_expected) do
{
'veteran' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '796111863',
'dateOfBirth' => '1809-02-12',
'homePhone' => '13035551234',
'email' => user.va_profile_email,
'address' => address
}
}
end
let(:vdispute_debt_expected) do
{
'veteran' => {
'fullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'ssn' => '1863',
'dateOfBirth' => '1809-02-12',
'homePhone' => us_phone,
'email' => user.va_profile_email,
'fileNumber' => '3735'
}
}
end
let(:initialize_va_profile_prefill_military_information_expected) do
expected_service_episodes_by_date = [
{
begin_date: '2012-03-02',
branch_of_service: 'Army',
branch_of_service_code: 'A',
character_of_discharge_code: nil,
deployments: [],
end_date: '2018-10-31',
period_of_service_type_code: 'N',
period_of_service_type_text: 'National Guard member',
service_type: 'Military Service',
termination_reason_code: 'C',
termination_reason_text: 'Completion of Active Service period'
},
{
begin_date: '2009-03-01',
branch_of_service: 'Navy',
branch_of_service_code: 'N',
character_of_discharge_code: nil,
deployments: [],
end_date: '2012-12-31',
period_of_service_type_code: 'N',
period_of_service_type_text: 'National Guard member',
service_type: 'Military Service',
termination_reason_code: 'C',
termination_reason_text: 'Completion of Active Service period'
},
{
begin_date: '2002-02-02',
branch_of_service: 'Army',
branch_of_service_code: 'A',
character_of_discharge_code: nil,
deployments: [],
end_date: '2008-12-01',
period_of_service_type_code: 'N',
period_of_service_type_text: 'National Guard member',
service_type: 'Military Service',
termination_reason_code: 'C',
termination_reason_text: 'Completion of Active Service period'
}
]
{
'currently_active_duty' => false,
'currently_active_duty_hash' => {
yes: false
},
'discharge_type' => nil,
'guard_reserve_service_history' => [
{
from: '2012-03-02',
to: '2018-10-31'
},
{
from: '2009-03-01',
to: '2012-12-31'
},
{
from: '2002-02-02',
to: '2008-12-01'
}
],
'hca_last_service_branch' => 'army',
'last_discharge_date' => '2018-10-31',
'last_entry_date' => '2012-03-02',
'last_service_branch' => 'Army',
'latest_guard_reserve_service_period' => {
from: '2012-03-02',
to: '2018-10-31'
},
'post_nov111998_combat' => false,
'service_branches' => %w[A N],
'service_episodes_by_date' => expected_service_episodes_by_date,
'service_periods' => [
{ service_branch: 'Army National Guard', date_range: { from: '2012-03-02', to: '2018-10-31' } },
{ service_branch: 'Army National Guard', date_range: { from: '2002-02-02', to: '2008-12-01' } }
],
'sw_asia_combat' => false,
'tours_of_duty' => [
{ service_branch: 'Army', date_range: { from: '2002-02-02', to: '2008-12-01' } },
{ service_branch: 'Navy', date_range: { from: '2009-03-01', to: '2012-12-31' } },
{ service_branch: 'Army', date_range: { from: '2012-03-02', to: '2018-10-31' } }
]
}
end
describe '#initialize_military_information', :skip_va_profile do
context 'with military_information vaprofile' do
it 'prefills military data from va profile' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
output = form_profile.send(:initialize_military_information).attribute_values.transform_keys(&:to_s)
expected_output = initialize_va_profile_prefill_military_information_expected
expected_output['vic_verified'] = false
actual_service_histories = output.delete('service_episodes_by_date')
actual_guard_reserve_service_history = output.delete('guard_reserve_service_history')
actual_latest_guard_reserve_service_period = output.delete('latest_guard_reserve_service_period')
expected_service_histories = expected_output.delete('service_episodes_by_date')
expected_guard_reserve_service_history = expected_output.delete('guard_reserve_service_history')
expected_latest_guard_reserve_service_period = expected_output.delete('latest_guard_reserve_service_period')
# Now that the nested structures are removed from the outputs, compare the rest of the structure.
expect(output).to eq(expected_output)
# Compare the nested structures VAProfile::Models::ServiceHistory objects separately.
expect(actual_service_histories.map(&:attributes)).to match(expected_service_histories)
first_item = actual_guard_reserve_service_history.map(&:attributes).first
expect(first_item['from'].to_s).to eq(expected_guard_reserve_service_history.first[:from])
expect(first_item['to'].to_s).to eq(expected_guard_reserve_service_history.first[:to])
guard_period = actual_latest_guard_reserve_service_period.attributes.transform_keys(&:to_s)
expect(guard_period['from'].to_s).to eq(expected_latest_guard_reserve_service_period[:from])
expect(guard_period['to'].to_s).to eq(expected_latest_guard_reserve_service_period[:to])
end
end
end
end
describe '#initialize_va_profile_prefill_military_information' do
context 'when va profile is down in production' do
it 'logs exception and returns empty hash' do
expect(form_profile).to receive(:log_exception_to_rails)
expect(form_profile.send(:initialize_va_profile_prefill_military_information)).to eq({})
end
end
it 'prefills military data from va profile' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true, match_requests_on: %i[method body]) do
output = form_profile.send(:initialize_va_profile_prefill_military_information)
# Extract service_episodes_by_date and then compare their attributes
actual_service_histories = output.delete('service_episodes_by_date')
expected_service_histories = initialize_va_profile_prefill_military_information_expected
.delete('service_episodes_by_date')
# Now that service_episodes_by_date is removed from output and from
# initialize_va_profile_prefill_military_information_expected, compare the rest of the structure.
expect(output).to eq(initialize_va_profile_prefill_military_information_expected)
# Compare service_episodes_by_date separately.
# Convert each VAProfile::Models::ServiceHistory object to a hash of attributes so it can be
# compared to the expected output.
expect(actual_service_histories.map(&:attributes)).to match(expected_service_histories)
end
end
end
describe '#prefill_form' do
def can_prefill_vaprofile(yes)
expect(user).to receive(:authorize).at_least(:once).with(:va_profile, :access?).and_return(yes)
end
def strip_required(schema)
new_schema = {}
schema.each do |k, v|
next if k == 'required'
new_schema[k] = v.is_a?(Hash) ? strip_required(v) : v
end
new_schema
end
def expect_prefilled(form_id)
prefilled_data = Oj.load(described_class.for(form_id:, user:).prefill.to_json)['form_data']
case form_id
when '1010ez', 'FORM-MOCK-AE-DESIGN-PATTERNS'
'10-10EZ'
when '21-526EZ'
'21-526EZ-ALLCLAIMS'
else
form_id
end.tap do |schema_form_id|
schema = strip_required(VetsJsonSchema::SCHEMAS[schema_form_id]).except('anyOf')
schema_data = prefilled_data.deep_dup
errors = JSON::Validator.fully_validate(
schema,
schema_data.deep_transform_keys { |key| key.camelize(:lower) }, validate_schema: true
)
expect(errors.empty?).to be(true), "schema errors: #{errors}"
end
expect(prefilled_data).to eq(
form_profile.send(:clean!, public_send("v#{form_id.underscore}_expected"))
)
end
context 'with a user that can prefill 10-10EZR' do
let(:form_profile) do
FormProfiles::VA1010ezr.new(user:, form_id: 'f')
end
let(:ezr_prefilled_data_without_ee_data) do
{
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
},
'veteranSocialSecurityNumber' => user.ssn,
'gender' => user.gender,
'veteranDateOfBirth' => user.birth_date,
'homePhone' => us_phone,
'veteranAddress' => address,
'email' => user.va_profile_email
}
end
context 'when the ee service is down' do
let(:v10_10_ezr_expected) { ezr_prefilled_data_without_ee_data.merge('nonPrefill' => {}) }
it 'prefills the rest of the data and logs exception to sentry' do
expect_any_instance_of(FormProfiles::VA1010ezr).to receive(:log_exception_to_sentry).with(
instance_of(VCR::Errors::UnhandledHTTPRequestError)
)
expect_prefilled('10-10EZR')
end
end
context 'with a user with financial data, insurance data, and dependents',
run_at: 'Thu, 27 Feb 2025 01:10:06 GMT' do
before do
allow(user).to receive(:icn).and_return('1012829228V424035')
allow(Flipper).to receive(:enabled?).and_call_original
end
context "when the 'ezr_form_prefill_with_providers_and_dependents' flipper is enabled" do
before do
allow(Flipper).to receive(:enabled?).with(:ezr_form_prefill_with_providers_and_dependents).and_return(true)
allow(Flipper).to receive(:enabled?).with(:ezr_emergency_contacts_enabled,
instance_of(User)).and_return(false)
end
let(:v10_10_ezr_expected) do
JSON.parse(
File.read('spec/fixtures/form1010_ezr/veteran_data.json')
).merge(ezr_prefilled_data_without_ee_data).except('nextOfKins', 'emergencyContacts')
end
it 'returns a prefilled 10-10EZR form', run_at: 'Thu, 27 Feb 2025 01:10:06 GMT' do
VCR.use_cassette(
'form1010_ezr/lookup_user_with_ezr_prefill_data',
match_requests_on: %i[method uri body], erb: true
) do
expect_prefilled('10-10EZR')
end
end
context "and the 'ezr_emergency_contacts_enabled' flipper is enabled" do
before do
allow(Flipper).to receive(:enabled?).with(:ezr_emergency_contacts_enabled,
instance_of(User)).and_return(true)
end
let(:v10_10_ezr_expected) do
contacts = JSON.parse(
File.read('spec/fixtures/form1010_ezr/veteran_data.json')
).merge(ezr_prefilled_data_without_ee_data)
contacts
end
it 'returns a prefilled 10-10EZR form', run_at: 'Thu, 27 Feb 2025 01:10:06 GMT' do
VCR.use_cassette(
'form1010_ezr/lookup_user_with_ezr_prefill_data',
match_requests_on: %i[method uri body], erb: true
) do
expect_prefilled('10-10EZR')
end
end
end
end
context "when the 'ezr_form_prefill_with_providers_and_dependents' flipper is disabled" do
before do
allow(Flipper).to receive(:enabled?).with(
:ezr_form_prefill_with_providers_and_dependents
).and_return(false)
allow(Flipper).to receive(:enabled?).with(:ezr_emergency_contacts_enabled,
instance_of(User)).and_return(false)
end
let(:v10_10_ezr_expected) do
JSON.parse(
File.read('spec/fixtures/form1010_ezr/veteran_data.json')
).merge(ezr_prefilled_data_without_ee_data).except(
'providers',
'dependents',
'nextOfKins',
'emergencyContacts'
)
end
it 'returns a prefilled 10-10EZR form that does not include providers, dependents, or contacts',
run_at: 'Thu, 27 Feb 2025 01:10:06 GMT' do
VCR.use_cassette(
'form1010_ezr/lookup_user_with_ezr_prefill_data',
match_requests_on: %i[method uri body], erb: true
) do
expect_prefilled('10-10EZR')
end
end
context "and the 'ezr_emergency_contacts_enabled' flipper is enabled" do
before do
allow(Flipper).to receive(:enabled?).with(:ezr_emergency_contacts_enabled,
instance_of(User)).and_return(true)
end
let(:v10_10_ezr_expected) do
JSON.parse(
File.read('spec/fixtures/form1010_ezr/veteran_data.json')
).merge(ezr_prefilled_data_without_ee_data).except('providers', 'dependents')
end
it 'returns a prefilled 10-10EZR form', run_at: 'Thu, 27 Feb 2025 01:10:06 GMT' do
VCR.use_cassette(
'form1010_ezr/lookup_user_with_ezr_prefill_data',
match_requests_on: %i[method uri body], erb: true
) do
expect_prefilled('10-10EZR')
end
end
end
end
end
end
context 'with a user that can prefill mdot' do
before do
expect(user).to receive(:authorize).with(:mdot, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:va_profile, :access?).and_return(true).at_least(:once)
expect(user.authorize(:mdot, :access?)).to be(true)
end
it 'returns a prefilled MDOT form', :skip_va_profile do
VCR.use_cassette('mdot/get_supplies_200') do
expect_prefilled('MDOT')
end
end
end
context 'with a user that can prefill DisputeDebt' do
before do
allow_any_instance_of(BGS::People::Service).to(
receive(:find_person_by_participant_id).and_return(BGS::People::Response.new({ file_nbr: '796043735' }))
)
end
it 'returns a prefilled DisputeDebt form' do
expect_prefilled('DISPUTE-DEBT')
end
end
context 'with a user that can prefill financial status report' do
let(:comp_and_pen_payments) do
[
{ payment_date: DateTime.now - 2.months, payment_amount: '1500' },
{ payment_date: DateTime.now - 10.days, payment_amount: '3000' }
]
end
before do
allow_any_instance_of(BGS::People::Service).to(
receive(:find_person_by_participant_id).and_return(BGS::People::Response.new({ file_nbr: '796043735' }))
)
allow_any_instance_of(User).to(
receive(:participant_id).and_return('600061742')
)
allow_any_instance_of(DebtManagementCenter::PaymentsService).to(
receive(:compensation_and_pension).and_return(comp_and_pen_payments)
)
allow_any_instance_of(DebtManagementCenter::PaymentsService).to(
receive(:education).and_return(nil)
)
allow(user).to receive(:authorize).and_return(true)
end
it 'returns a prefilled 5655 form' do
expect_prefilled('5655')
end
context 'payment window' do
let(:education_payments) do
[
{ payment_date: DateTime.now - 3.months, payment_amount: '1500' }
]
end
before do
allow_any_instance_of(DebtManagementCenter::PaymentsService).to(
receive(:education).and_return(education_payments)
)
end
it 'filters older payments when window is present' do
allow(Settings.dmc).to receive(:fsr_payment_window).and_return(30)
expect_prefilled('5655')
end
context 'no window present' do
let(:v5655_expected) do
{
'personalIdentification' => {
'ssn' => user.ssn.last(4),
'fileNumber' => '3735'
},
'personalData' => {
'veteranFullName' => full_name,
'address' => address,
'telephoneNumber' => us_phone,
'emailAddress' => user.va_profile_email,
'dateOfBirth' => user.birth_date
},
'income' => [
{
'veteranOrSpouse' => 'VETERAN',
'compensationAndPension' => '3000',
'education' => '1500'
}
]
}
end
it 'includes older payments when no window is present' do
allow(Settings.dmc).to receive(:fsr_payment_window).and_return(nil)
expect_prefilled('5655')
end
end
end
end
context 'when VA Profile returns 404', :skip_va_profile do
it 'returns default values' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_history_404',
allow_playback_repeats: true, match_requests_on: %i[method body]) do
can_prefill_vaprofile(true)
output = form_profile.send(:initialize_military_information).attributes.transform_keys(&:to_s)
expect(output['currently_active_duty']).to be(false)
expect(output['currently_active_duty_hash']).to match({ yes: false })
expect(output['discharge_type']).to be_nil
expect(output['guard_reserve_service_history']).to eq([])
expect(output['hca_last_service_branch']).to eq('other')
expect(output['last_discharge_date']).to be_nil
expect(output['last_entry_date']).to be_nil
expect(output['last_service_branch']).to be_nil
expect(output['latest_guard_reserve_service_period']).to be_nil
expect(output['post_nov111998_combat']).to be(false)
expect(output['service_branches']).to eq([])
expect(output['service_episodes_by_date']).to eq([])
expect(output['service_periods']).to eq([])
expect(output['sw_asia_combat']).to be(false)
expect(output['tours_of_duty']).to eq([])
end
end
end
context 'when VA Profile returns 500', :skip_va_profile do
it 'sends a BackendServiceException to Sentry and returns and empty hash' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_history_500',
allow_playback_repeats: true, match_requests_on: %i[method uri]) do
expect(form_profile).to receive(:log_exception_to_rails)
expect(form_profile.send(:initialize_va_profile_prefill_military_information)).to eq({})
end
end
end
context 'with military information data', :skip_va_profile do
context 'with va profile prefill on' do
before do
VAProfile::Configuration::SETTINGS.prefill = true
v22_1990_expected['email'] = VAProfileRedis::V2::ContactInformation.for_user(user).email.email_address
v22_1990_expected['homePhone'] = '3035551234'
v22_1990_expected['mobilePhone'] = '3035551234'
v22_1990_expected['veteranAddress'] = address
end
after do
VAProfile::Configuration::SETTINGS.prefill = false
end
it 'prefills 1990' do
VCR.use_cassette('va_profile/military_personnel/service_history_200_many_episodes',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
expect_prefilled('22-1990')
end
end
end
context 'with VA Profile prefill for 0994' do
before do
expect(user).to receive(:authorize).with(:ppiu, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:va_profile, :access?).and_return(true).at_least(:once)
end
it 'prefills 0994' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('22-0994')
end
end
end
context 'with VA Profile and ppiu prefill for 0994' do
before do
can_prefill_vaprofile(true)
expect(user).to receive(:authorize).with(:ppiu, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once)
end
it 'prefills 0994 with VA Profile and payment information' do
VCR.use_cassette('va_profile/v2/contact_information/get_address') do
VCR.use_cassette('evss/disability_compensation_form/rated_disabilities') do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('22-0994')
end
end
end
end
end
context 'with VA Profile prefill for 0873' do
let(:info) do
{
SchoolFacilityCode: '12345678',
BusinessPhone: '1234567890',
BusinessEmail: 'fake@company.com',
ServiceNumber: '123455678'
}
end
let(:profile) do
AskVAApi::Profile::Entity.new(info)
end
let(:body) do
{
data: {
attributes: {
name: 'Fake School'
}
}
}
end
let(:gids_response) do
GI::GIDSResponse.new(status: 200, body:)
end
before do
allow_any_instance_of(AskVAApi::Profile::Retriever).to receive(:call).and_return(profile)
allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0).and_return(gids_response)
end
context 'when CRM profile is working' do
it 'prefills 0873' do
VCR.use_cassette('va_profile/demographics/demographics', VCR::MATCH_EVERYTHING) do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
expect_prefilled('0873')
end
end
end
end
context 'when school facility code is nil' do
let(:info) do
{
SchoolFacilityCode: nil,
BusinessPhone: '1234567890',
BusinessEmail: 'fake@company.com',
ServiceNumber: '123455678'
}
end
let(:v0873_expected) do
{
'personalInformation' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix,
'preferredName' => 'SAM',
'dateOfBirth' => user.birth_date,
'socialSecurityNumber' => user.ssn,
'serviceNumber' => '123455678'
},
'contactInformation' => {
'email' => user.va_profile_email,
'phone' => us_phone,
'workPhone' => '13035551234',
'address' => address
},
'avaProfile' => {
'businessPhone' => '1234567890',
'businessEmail' => 'fake@company.com'
},
'veteranServiceInformation' => veteran_service_information
}
end
it 'does not show in ava profile' do
VCR.use_cassette('va_profile/demographics/demographics', VCR::MATCH_EVERYTHING) do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
expect_prefilled('0873')
end
end
end
end
end
context 'with VA Profile prefill for 10203' do
before do
expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:va_profile, :access?).and_return(true).at_least(:once)
end
it 'prefills 10203' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('22-10203')
end
end
end
context 'with VA Profile and GiBillStatus prefill for 10203' do
before do
can_prefill_vaprofile(true)
expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once)
v22_10203_expected['remainingEntitlement'] = {
'months' => 0,
'days' => 10
}
v22_10203_expected['schoolName'] = 'OLD DOMINION UNIVERSITY'
v22_10203_expected['schoolCity'] = 'NORFOLK'
v22_10203_expected['schoolState'] = 'VA'
v22_10203_expected['schoolCountry'] = 'USA'
end
it 'prefills 10203 with VA Profile and entitlement information' do
VCR.use_cassette('va_profile/v2/contact_information/get_address') do
VCR.use_cassette('evss/disability_compensation_form/rated_disabilities') do
VCR.use_cassette('form_10203/gi_bill_status_200_response') do
VCR.use_cassette('gi_client/gets_the_institution_details') do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect(BenefitsEducation::Service).to receive(:new).with(user.icn).and_call_original
prefilled_data = Oj.load(
described_class.for(form_id: '22-10203', user:).prefill.to_json
)['form_data']
actual = form_profile.send(:clean!, v22_10203_expected)
expect(prefilled_data).to eq(actual)
end
end
end
end
end
end
end
context 'with a user that can prefill VA Profile' do
before do
can_prefill_vaprofile(true)
end
context 'with a 686c-674 form v3 enabled' do
let(:v686_c_674_v2_expected) do
{
'veteranContactInformation' => {
'veteranAddress' => {
'street' => '140 Rock Creek Rd',
'country' => 'USA',
'city' => 'Washington',
'state' => 'DC',
'postalCode' => '20011'
},
'phoneNumber' => us_phone,
'emailAddress' => user.va_profile_email
},
'nonPrefill' => {
'dependents' => {
'success' => 'false'
},
'veteranSsnLastFour' => '1863',
'veteranVaFileNumberLastFour' => '1863',
'isInReceiptOfPension' => -1,
'netWorthLimit' => 163_699
},
'veteranInformation' => {
'fullName' => {
'first' => user.first_name.capitalize,
'last' => user.last_name.capitalize
},
'ssn' => '796111863',
'birthDate' => '1809-02-12'
}
}
end
before do
allow(Flipper).to receive(:enabled?).with(:va_dependents_v3, anything).and_return(true)
end
context 'with a 686c-674 v1 form' do
it 'omits address fields in 686c-674 form' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('686C-674')
end
end
end
context 'with a 686c-674-v2 form' do
it 'omits address fields in 686c-674-V2 form' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('686C-674-V2')
end
end
context 'with pension awards prefill' do
let(:user) { create(:evss_user, :loa3) }
let(:form_profile) do
FormProfiles::VA686c674v2.new(user:, form_id: '686C-674-V2')
end
before do
allow(Rails.logger).to receive(:warn)
end
it 'prefills net worth limit' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
VCR.use_cassette('bid/awards/get_awards_pension') do
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(prefilled_data['nonPrefill']['netWorthLimit']).to eq(129094) # rubocop:disable Style/NumericLiterals
end
end
end
it 'prefills 1 when user is in receipt of pension' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
VCR.use_cassette('bid/awards/get_awards_pension') do
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(1)
end
end
end
it 'prefills 0 when user is not in receipt of pension' do
prefill_no_receipt_of_pension = {
is_in_receipt_of_pension: false
}
form_profile_instance = described_class.for(form_id: '686C-674-V2', user:)
allow(form_profile_instance).to receive(:awards_pension).and_return(prefill_no_receipt_of_pension)
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
prefilled_data = form_profile_instance.prefill[:form_data]
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(0)
end
end
it 'prefills -1 and default net worth limit when bid awards service returns an error' do
error = StandardError.new('awards pension error')
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
allow_any_instance_of(BID::Awards::Service).to receive(:get_awards_pension).and_raise(error)
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(Rails.logger)
.to have_received(:warn)
.with(
'Failed to retrieve awards pension data', {
user_account_uuid: user&.user_account_uuid,
error: error.message,
form_id: '686C-674-V2'
}
)
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(-1)
expect(prefilled_data['nonPrefill']['netWorthLimit']).to eq(163_699)
end
end
end
context 'with dependents prefill' do
let(:user) { create(:evss_user, :loa3) }
let(:form_profile) do
FormProfiles::VA686c674v2.new(user:, form_id: '686C-674-V2')
end
let(:dependent_service) { instance_double(BGS::DependentService) }
let(:dependents_data) do
{ number_of_records: '1', persons: [{
award_indicator: 'Y',
date_of_birth: '01/02/1960',
email_address: 'test@email.com',
first_name: 'JANE',
last_name: 'WEBB',
middle_name: 'M',
ptcpnt_id: '600140899',
related_to_vet: 'Y',
relationship: 'Spouse',
ssn: '222883214',
veteran_indicator: 'N'
}] }
end
let(:dependents_information) do
[{
'fullName' => { 'first' => 'JANE', 'middle' => 'M', 'last' => 'WEBB' },
'dateOfBirth' => '1960-01-02',
'ssn' => '222883214',
'relationshipToVeteran' => 'Spouse',
'awardIndicator' => 'Y'
}]
end
before do
allow(Rails.logger).to receive(:warn)
end
it 'returns formatted dependent information' do
# Mock the dependent service to return active dependents
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(dependents_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
expect(result[:form_data]['nonPrefill']['dependents']['dependents']).to eq(dependents_information)
end
it 'handles a dependent information error' do
# Mock the dependent service to return an error
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_raise(
StandardError.new('Dependent information error')
)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']['dependents']).not_to have_key('dependents')
end
it 'handles missing dependents data' do
# Mock the dependent service to return no dependents
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(nil)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']['dependents']).not_to have_key('dependents')
end
it 'handles invalid date formats gracefully' do
invalid_date_data = dependents_data.dup
invalid_date_data[:persons][0][:date_of_birth] = 'invalid-date'
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(invalid_date_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
dependents = result[:form_data]['nonPrefill']['dependents']
expect(dependents).to be_an(Object)
expect(dependents['dependents'].first['dateOfBirth']).to be_nil
end
it 'handles nil date gracefully' do
nil_date_data = dependents_data.dup
nil_date_data[:persons][0][:date_of_birth] = nil
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(nil_date_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
dependents = result[:form_data]['nonPrefill']['dependents']
expect(dependents).to be_an(Object)
expect(dependents['dependents'].first['dateOfBirth']).to be_nil
end
end
end
end
context 'with a 686c-674 form v3 disabled' do
before do
allow(Flipper).to receive(:enabled?).with(:va_dependents_v3, anything).and_return(false)
end
context 'with a 686c-674 v1 form' do
it 'omits address fields in 686c-674 form' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('686C-674')
end
end
end
context 'with a 686c-674-v2 form' do
it 'omits address fields in 686c-674-V2 form' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
expect_prefilled('686C-674-V2')
end
end
context 'with pension awards prefill' do
let(:user) { create(:evss_user, :loa3) }
let(:form_profile) do
FormProfiles::VA686c674v2.new(user:, form_id: '686C-674-V2')
end
before do
allow(Rails.logger).to receive(:warn)
end
it 'prefills net worth limit' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
VCR.use_cassette('bid/awards/get_awards_pension') do
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(prefilled_data['nonPrefill']['netWorthLimit']).to eq(129094) # rubocop:disable Style/NumericLiterals
end
end
end
it 'prefills 1 when user is in receipt of pension' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
VCR.use_cassette('bid/awards/get_awards_pension') do
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(1)
end
end
end
it 'prefills 0 when user is not in receipt of pension' do
prefill_no_receipt_of_pension = {
is_in_receipt_of_pension: false
}
form_profile_instance = described_class.for(form_id: '686C-674-V2', user:)
allow(form_profile_instance).to receive(:awards_pension).and_return(prefill_no_receipt_of_pension)
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
prefilled_data = form_profile_instance.prefill[:form_data]
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(0)
end
end
it 'prefills -1 and default net worth limit when bid awards service returns an error' do
error = StandardError.new('awards pension error')
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200',
allow_playback_repeats: true) do
allow_any_instance_of(BID::Awards::Service).to receive(:get_awards_pension).and_raise(error)
prefilled_data = described_class.for(form_id: '686C-674-V2', user:).prefill[:form_data]
expect(Rails.logger)
.to have_received(:warn)
.with(
'Failed to retrieve awards pension data', {
user_account_uuid: user&.user_account_uuid,
error: error.message,
form_id: '686C-674-V2'
}
)
expect(prefilled_data['nonPrefill']['isInReceiptOfPension']).to eq(-1)
expect(prefilled_data['nonPrefill']['netWorthLimit']).to eq(163_699)
end
end
end
context 'with dependents prefill' do
let(:user) { create(:evss_user, :loa3) }
let(:form_profile) do
FormProfiles::VA686c674v2.new(user:, form_id: '686C-674-V2')
end
let(:dependent_service) { instance_double(BGS::DependentService) }
let(:dependents_data) do
{ number_of_records: '1', persons: [{
award_indicator: 'Y',
date_of_birth: '01/02/1960',
email_address: 'test@email.com',
first_name: 'JANE',
last_name: 'WEBB',
middle_name: 'M',
ptcpnt_id: '600140899',
related_to_vet: 'Y',
relationship: 'Spouse',
ssn: '222883214',
veteran_indicator: 'N'
}] }
end
let(:dependents_information) do
[{
'fullName' => { 'first' => 'JANE', 'middle' => 'M', 'last' => 'WEBB' },
'dateOfBirth' => '1960-01-02',
'ssn' => '222883214',
'relationshipToVeteran' => 'Spouse',
'awardIndicator' => 'Y'
}]
end
before do
allow(Rails.logger).to receive(:warn)
end
it 'returns formatted dependent information' do
# Mock the dependent service to return active dependents
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(dependents_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
expect(result[:form_data]['nonPrefill']['dependents']).to eq(dependents_information)
end
it 'handles a dependent information error' do
# Mock the dependent service to return an error
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_raise(
StandardError.new('Dependent information error')
)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).not_to have_key('dependents')
end
it 'handles missing dependents data' do
# Mock the dependent service to return no dependents
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(nil)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranInformation')
expect(result[:form_data]).to have_key('veteranContactInformation')
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).not_to have_key('dependents')
end
it 'handles invalid date formats gracefully' do
invalid_date_data = dependents_data.dup
invalid_date_data[:persons][0][:date_of_birth] = 'invalid-date'
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(invalid_date_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
dependents = result[:form_data]['nonPrefill']['dependents']
expect(dependents).to be_an(Array)
expect(dependents.first['dateOfBirth']).to be_nil
end
it 'handles nil date gracefully' do
nil_date_data = dependents_data.dup
nil_date_data[:persons][0][:date_of_birth] = nil
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return(nil_date_data)
result = form_profile.prefill
expect(result[:form_data]).to have_key('nonPrefill')
expect(result[:form_data]['nonPrefill']).to have_key('dependents')
dependents = result[:form_data]['nonPrefill']['dependents']
expect(dependents).to be_an(Array)
expect(dependents.first['dateOfBirth']).to be_nil
end
end
context 'with address prefill' do
let(:user) { create(:evss_user, :loa3) }
let(:form_profile) do
FormProfiles::VA686c674v2.new(user:, form_id: '686C-674-V2')
end
let(:contact_info_service) { instance_double(VAProfileRedis::V2::ContactInformation) }
let(:dependent_service) { instance_double(BGS::DependentService) }
let(:email_double) { instance_double(VAProfile::Models::Email, email_address: 'test@example.com') }
let(:home_phone_double) { instance_double(VAProfile::Models::Telephone, formatted_phone: '5035551234') }
let(:mobile_phone_double) { instance_double(VAProfile::Models::Telephone, formatted_phone: '5035555678') }
before do
# Mock VAProfile contact info for both user and form profile usage
allow(VAProfileRedis::V2::ContactInformation).to receive(:for_user).with(user).and_return(
contact_info_service
)
allow(contact_info_service).to receive_messages(email: email_double, home_phone: home_phone_double,
mobile_phone: mobile_phone_double)
# Mock dependent service to avoid BGS calls
allow(BGS::DependentService).to receive(:new).with(user).and_return(dependent_service)
allow(dependent_service).to receive(:get_dependents).and_return({ persons: [] })
# Mock BID awards service
allow_any_instance_of(BID::Awards::Service).to receive(:get_awards_pension).and_return(
OpenStruct.new(body: { 'awards_pension' => { 'is_in_receipt_of_pension' => false } })
)
end
context 'with domestic address' do
let(:domestic_address) do
build(:va_profile_address,
:mailing,
:domestic,
address_line1: '123 Main St',
address_line2: 'Apt 4B',
address_line3: 'Building C',
city: 'Portland',
state_code: 'OR',
zip_code: '97201',
country_code_iso3: 'USA')
end
it 'prefills address with zip_code when available' do
allow(contact_info_service).to receive(:mailing_address).and_return(domestic_address)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranContactInformation')
vet_contact = result[:form_data]['veteranContactInformation']
expect(vet_contact).to have_key('veteranAddress')
vet_address = vet_contact['veteranAddress']
expect(vet_address['street']).to eq('123 Main St')
expect(vet_address['street2']).to eq('Apt 4B')
expect(vet_address['street3']).to eq('Building C')
expect(vet_address['city']).to eq('Portland')
expect(vet_address['state']).to eq('OR')
expect(vet_address['postalCode']).to eq('97201')
expect(vet_address['country']).to eq('USA')
end
end
context 'with international address' do
let(:international_address) do
build(:va_profile_address,
:mailing,
:international,
address_line1: '10 Downing Street',
city: 'London',
province: 'Greater London',
international_postal_code: 'SW1A 2AA',
country_code_iso3: 'GBR',
zip_code: nil,
state_code: nil)
end
it 'prefills address with international_postal_code when zip_code is nil' do
allow(contact_info_service).to receive(:mailing_address).and_return(international_address)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranContactInformation')
vet_contact = result[:form_data]['veteranContactInformation']
expect(vet_contact).to have_key('veteranAddress')
vet_address = vet_contact['veteranAddress']
expect(vet_address['street']).to eq('10 Downing Street')
expect(vet_address['city']).to eq('London')
expect(vet_address['postalCode']).to eq('SW1A 2AA')
expect(vet_address['country']).to eq('GBR')
expect(vet_address['state']).to be_nil
end
end
context 'when mailing address is blank' do
it 'does not prefill address' do
allow(contact_info_service).to receive(:mailing_address).and_return(nil)
result = form_profile.prefill
expect(result[:form_data]).to have_key('veteranContactInformation')
# veteranContactInformation will have other fields but not veteranAddress
expect(result[:form_data]['veteranContactInformation']).not_to have_key('veteranAddress')
end
end
end
end
end
%w[
21P-527EZ
22-1990
22-1995
22-5490
22-5495
40-10007
1010ez
22-0993
FEEDBACK-TOOL
686C-674
28-8832
28-1900
26-1880
26-4555
21-22
21-22A
21-2680
FORM-MOCK-AE-DESIGN-PATTERNS
].each do |form_id|
it "returns prefilled #{form_id}" do
allow(Flipper).to receive(:enabled?).with(:pension_military_prefill, anything).and_return(false)
VCR.use_cassette('va_profile/military_personnel/service_history_200_many_episodes',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
expect_prefilled(form_id)
end
end
end
context 'when Vet360 prefill is enabled' do
let(:user) do
build(:user, :loa3, :legacy_icn, suffix: 'Jr.', address: build(:va_profile_address),
vet360_id: '1781151')
end
before do
VAProfile::Configuration::SETTINGS.prefill = true # TODO: - is this missing in the failures above?
expected_veteran_info = v21_526_ez_expected['veteran']
expected_veteran_info['emailAddress'] = user.va_profile_email
expected_veteran_info['primaryPhone'] = us_phone
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_token')
end
after do
VAProfile::Configuration::SETTINGS.prefill = false
end
it 'returns prefilled 21-526EZ' do
expect(user).to receive(:authorize).with(:lighthouse, :direct_deposit_access?)
.and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:evss, :access?).and_return(true).at_least(:once)
expect(user).to receive(:authorize).with(:va_profile, :access_to_v2?).and_return(true).at_least(:once)
VCR.use_cassette('va_profile/v2/contact_information/get_address') do
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
VCR.use_cassette('lighthouse/direct_deposit/show/200_valid_new_icn') do
VCR.use_cassette('va_profile/military_personnel/service_history_200_many_episodes',
allow_playback_repeats: true, match_requests_on: %i[uri method body]) do
VCR.use_cassette('disability_max_ratings/max_ratings') do
expect_prefilled('21-526EZ')
end
end
end
end
end
end
end
end
end
context 'with a burial application form' do
it 'returns the va profile mapped to the burial form' do
expect_prefilled('21P-530EZ')
end
context 'without address' do
let(:v21_p_530_ez_expected) do
{
'claimantFullName' => {
'first' => user.first_name&.capitalize,
'middle' => user.middle_name&.capitalize,
'last' => user.last_name&.capitalize,
'suffix' => user.suffix
}
}
end
before do
allow_any_instance_of(Burials::FormProfiles::VA21p530ez)
.to receive(:initialize_contact_information).and_return(FormContactInformation.new)
end
it "doesn't throw an exception" do
expect_prefilled('21P-530EZ')
end
end
end
context 'with a higher level review form' do
let(:schema_name) { '20-0996' }
let(:schema) { VetsJsonSchema::SCHEMAS[schema_name] }
let(:form_profile) { described_class.for(form_id: schema_name, user:) }
let(:prefill) { Oj.load(form_profile.prefill.to_json)['form_data'] }
before do
allow_any_instance_of(BGS::People::Service).to(
receive(:find_person_by_participant_id).and_return(BGS::People::Response.new({ file_nbr: '1234567890' }))
)
allow_any_instance_of(VAProfile::Models::Address).to(
receive(:address_line3).and_return('suite 500')
)
end
it 'street3 returns VAProfile address_line3' do
expect(form_profile.send(:vet360_mailing_address)&.address_line3).to eq form_profile.send :street3
end
it 'prefills' do
expect(prefill.dig('nonPrefill', 'veteranSsnLastFour')).to be_a(String).or be_nil
expect(prefill.dig('nonPrefill', 'veteranVaFileNumberLastFour')).to be_a(String)
end
it 'prefills an object that passes the schema' do
full_example = VetsJsonSchema::EXAMPLES['HLR-CREATE-REQUEST-BODY']
test_data = full_example.deep_merge prefill
errors = JSON::Validator.fully_validate(
schema,
test_data,
validate_schema: true
)
expect(errors.empty?).to be(true), "schema errors: #{errors}"
end
end
context 'with a notice of disagreement (NOD) form' do
let(:schema_name) { '10182' }
let(:schema) do
DecisionReview::Schemas::NOD_CREATE_REQUEST.merge '$schema': 'http://json-schema.org/draft-04/schema#'
end
let(:form_profile) { described_class.for(form_id: schema_name, user:) }
let(:prefill) { Oj.load(form_profile.prefill.to_json)['form_data'] }
before do
allow_any_instance_of(BGS::People::Service).to(
receive(:find_person_by_participant_id).and_return(BGS::People::Response.new({ file_nbr: '1234567890' }))
)
allow_any_instance_of(VAProfile::Models::Address).to(
receive(:address_line3).and_return('suite 500')
)
end
it 'street3 returns VAProfile address_line3' do
expect(form_profile.send(:vet360_mailing_address)&.address_line3).to eq form_profile.send :street3
end
it 'prefills' do
non_prefill = prefill['nonPrefill']
expect(non_prefill['veteranSsnLastFour']).to be_a String
expect(non_prefill['veteranVaFileNumberLastFour']).to be_a String
end
it 'prefills an object that passes the schema' do
full_example = JSON.parse Rails.root.join('spec', 'fixtures', 'notice_of_disagreements',
'valid_NOD_create_request.json').read
test_data = full_example.deep_merge prefill.except('nonPrefill')
errors = JSON::Validator.fully_validate(
schema,
test_data,
validate_schema: true
)
expect(errors.empty?).to be(true), "schema errors: #{errors}"
end
end
context 'when the form mapping can not be found' do
it 'raises an IOError' do
allow(FormProfile).to receive(:prefill_enabled_forms).and_return(['foo'])
expect { described_class.new(form_id: 'foo', user:).prefill }.to raise_error(IOError)
end
end
context 'when the form does not use prefill' do
it 'does not raise an error' do
expect { described_class.new(form_id: '21-4142', user:).prefill }.not_to raise_error
end
end
end
describe '.mappings_for_form' do
context 'with multiple form profile instances' do
let(:instance1) { FormProfile.new(form_id: '1010ez', user:) }
let(:instance2) { FormProfile.new(form_id: '1010ez', user:) }
it 'loads the yaml file only once' do
expect(YAML).to receive(:load_file).once.and_return(
'veteran_full_name' => %w[identity_information full_name],
'gender' => %w[identity_information gender],
'veteran_date_of_birth' => %w[identity_information date_of_birth],
'veteran_address' => %w[contact_information address],
'home_phone' => %w[contact_information home_phone]
)
instance1.prefill
instance2.prefill
end
end
end
describe 'loading 10-7959C form mappings' do
it "doesn't raise an IOError" do
expect { FormProfile.load_form_mapping('10-7959C') }.not_to raise_error
end
it 'loads the correct data' do
mapping_file = Rails.root.join('config', 'form_profile_mappings', '10-7959C.yml')
mappings = YAML.load_file(mapping_file)
expect(FormProfile.load_form_mapping('10-7959C')).to match(mappings)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/prescription_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe Prescription do
let(:prescription_attributes) { attributes_for(:prescription) }
context 'with valid attributes' do
subject { described_class.new(prescription_attributes) }
it 'has attributes' do
expect(subject).to have_attributes(refill_status: 'active', refill_remaining: 9, facility_name: 'ABC1223',
is_refillable: true, is_trackable: false, prescription_id: 1_435_525,
quantity: '10', prescription_number: '2719324',
prescription_name: 'Drug 1 250MG TAB', station_number: '23')
end
it 'has additional aliased rubyesque methods' do
expect(subject).to have_attributes(trackable?: false, refillable?: true)
end
it 'has date attributes' do
expect(subject).to have_attributes(refill_submit_date: Time.parse('Tue, 26 Apr 2016 00:00:00 EDT').in_time_zone,
refill_date: Time.parse('Thu, 21 Apr 2016 00:00:00 EDT').in_time_zone,
ordered_date: Time.parse('Tue, 29 Mar 2016 00:00:00 EDT').in_time_zone,
expiration_date: Time.parse('Thu, 30 Mar 2017 00:00:00 EDT').in_time_zone,
dispensed_date: Time.parse('Thu, 21 Apr 2016 00:00:00 EDT').in_time_zone)
end
context 'inherited methods' do
it 'responds to to_json' do
expect(subject.to_json).to be_a(String)
end
end
end
context 'it sorts' do
subject { [p1, p2, p3, p4] }
let(:p1) { described_class.new(prescription_attributes) }
let(:p2) { described_class.new(prescription_attributes) }
let(:p3) { described_class.new(attributes_for(:prescription, prescription_id: '2', refill_date: Time.now.utc)) }
let(:p4) { described_class.new(attributes_for(:prescription, prescription_id: '3', refill_data: 1.year.ago.utc)) }
it 'sorts by prescription_id by default' do
expect(subject.sort.map(&:prescription_id))
.to eq([2, 3, 1_435_525, 1_435_525])
end
it 'sorts by sort_by field' do
expect(subject.sort_by(&:refill_date).map(&:prescription_id))
.to eq([1_435_525, 1_435_525, 3, 2])
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/decision_review_notification_audit_log_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DecisionReviewNotificationAuditLog, type: :model do
let(:audit_log) { build(:decision_review_notification_audit_log) }
describe 'payload encryption' do
it 'encrypts the payload field' do
expect(subject).to encrypt_attr(:payload)
end
end
describe 'validations' do
it 'validates presence of payload' do
expect_attr_valid(audit_log, :payload)
audit_log.payload = nil
expect_attr_invalid(audit_log, :payload, "can't be blank")
end
end
describe '#serialize_payload' do
let(:payload) do
{ a: 1 }
end
it 'serializes payload as json' do
audit_log.payload = payload
audit_log.save!
expect(audit_log.payload).to eq(payload.to_json)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_verification_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserVerification, type: :model do
let(:user_verification) do
create(:user_verification,
idme_uuid:,
logingov_uuid:,
dslogon_uuid:,
mhv_uuid:,
backing_idme_uuid:,
verified_at:,
user_account_id: user_account&.id,
locked:)
end
let(:idme_uuid) { nil }
let(:logingov_uuid) { nil }
let(:dslogon_uuid) { nil }
let(:mhv_uuid) { nil }
let(:user_account) { nil }
let(:backing_idme_uuid) { nil }
let(:verified_at) { nil }
let(:locked) { false }
describe 'validations' do
shared_examples 'failed credential identifier validation' do
let(:expected_error_message) { 'Validation failed: Must specify one, and only one, credential identifier' }
it 'raises validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
shared_examples 'failed backing uuid credentials validation' do
let(:expected_error_message) do
'Validation failed: Must define either an idme_uuid, logingov_uuid, or backing_idme_uuid'
end
it 'raises validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
shared_examples 'failed both validations' do
let(:expected_error_message) do
'Validation failed: Must specify one, and only one, credential identifier, ' \
'Must define either an idme_uuid, logingov_uuid, or backing_idme_uuid'
end
it 'raises validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
describe '#user_account' do
subject { user_verification.user_account }
let(:idme_uuid) { 'banana' }
context 'when user_account is nil' do
let(:user_account) { nil }
let(:expected_error_message) { 'Validation failed: User account must exist' }
it 'raises validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
context 'when user_account is not nil' do
let(:user_account) { create(:user_account) }
it 'returns the user account' do
expect(subject).to eq(user_account)
end
end
end
describe '#idme_uuid' do
subject { user_verification.idme_uuid }
let(:user_account) { create(:user_account) }
context 'when another credential is defined' do
let(:logingov_uuid) { 'some-logingov-id' }
context 'and idme_uuid is not defined' do
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'and idme_uuid is defined' do
let(:idme_uuid) { 'some-idme-uuid' }
it_behaves_like 'failed credential identifier validation'
end
end
context 'when another credential is not defined' do
context 'and idme_uuid is not defined' do
let(:idme_uuid) { nil }
it_behaves_like 'failed both validations'
end
context 'and idme_uuid is defined' do
let(:idme_uuid) { 'some-idme-uuid' }
it 'returns idme_uuid' do
expect(subject).to eq(idme_uuid)
end
end
end
end
describe '#logingov_uuid' do
subject { user_verification.logingov_uuid }
let(:user_account) { create(:user_account) }
context 'when another credential is defined' do
let(:idme_uuid) { 'some-idme-uuid-id' }
context 'and logingov_uuid is not defined' do
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'and logingov_uuid is defined' do
let(:logingov_uuid) { 'some-logingov-uuid' }
it_behaves_like 'failed credential identifier validation'
end
end
context 'when another credential is not defined' do
context 'and logingov_uuid is not defined' do
let(:logingov_uuid) { nil }
it_behaves_like 'failed both validations'
end
context 'and logingov_uuid is defined' do
let(:logingov_uuid) { 'some-logingov-uuid' }
it 'returns logingov_uuid' do
expect(subject).to eq(logingov_uuid)
end
end
end
end
describe '#dslogon_uuid' do
subject { user_verification.dslogon_uuid }
let(:user_account) { create(:user_account) }
context 'when another credential is defined' do
let(:idme_uuid) { 'some-idme-uuid-id' }
context 'and dslogon_uuid is not defined' do
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'and dslogon_uuid is defined' do
let(:dslogon_uuid) { 'some-dslogon-uuid' }
it_behaves_like 'failed credential identifier validation'
end
end
context 'when another credential is not defined' do
context 'and dslogon_uuid is not defined' do
let(:dslogon_uuid) { nil }
it_behaves_like 'failed both validations'
end
context 'and dslogon_uuid is defined' do
let(:dslogon_uuid) { 'some-dslogon-uuid' }
context 'and backing_idme_uuid is not defined' do
let(:backing_idme_uuid) { nil }
it_behaves_like 'failed backing uuid credentials validation'
end
context 'and backing_idme_uuid is defined' do
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
it 'returns dslogon_uuid' do
expect(subject).to eq(dslogon_uuid)
end
end
end
end
end
describe '#mhv_uuid' do
subject { user_verification.mhv_uuid }
let(:user_account) { create(:user_account) }
context 'when another credential is defined' do
let(:idme_uuid) { 'some-idme-uuid-id' }
context 'and mhv_uuid is not defined' do
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'and mhv_uuid is defined' do
let(:mhv_uuid) { 'some-mhv-uuid' }
it_behaves_like 'failed credential identifier validation'
end
end
context 'when another credential is not defined' do
context 'and mhv_uuid is not defined' do
let(:mhv_uuid) { nil }
it_behaves_like 'failed both validations'
end
context 'and mhv_uuid is defined' do
let(:mhv_uuid) { 'some-mhv-uuid' }
context 'and backing_idme_uuid is not defined' do
let(:backing_idme_uuid) { nil }
it_behaves_like 'failed backing uuid credentials validation'
end
context 'and backing_idme_uuid is defined' do
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
it 'returns mhv_uuid' do
expect(subject).to eq(mhv_uuid)
end
end
end
end
end
end
describe '.lock!' do
subject { user_verification.lock! }
let(:user_account) { create(:user_account) }
let(:logingov_uuid) { SecureRandom.uuid }
it 'updates locked to true' do
expect { subject }.to change(user_verification, :locked).from(false).to(true)
end
end
describe '.unlock!' do
subject { user_verification.unlock! }
let(:user_account) { create(:user_account) }
let(:logingov_uuid) { SecureRandom.uuid }
let(:locked) { true }
it 'updates locked to false' do
expect { subject }.to change(user_verification, :locked).from(true).to(false)
end
end
describe '.find_by_type!' do
subject { UserVerification.find_by_type!(type, identifier) }
let(:user_account) { create(:user_account) }
context 'when a user verification is not found' do
let(:identifier) { 'some-identifier' }
let(:type) { 'logingov' }
it 'raises a record not found error' do
expect { subject }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context 'when a user verification is found' do
let(:identifier) { user_verification.credential_identifier }
context 'when a Login.gov user verification is found' do
let(:logingov_uuid) { 'some-logingov-uuid' }
let(:type) { 'logingov' }
it 'returns the user verification' do
expect(subject).to eq(user_verification)
end
end
context 'when an ID.me user verification is found' do
let(:idme_uuid) { 'some-idme-uuid' }
let(:type) { 'idme' }
it 'returns the user verification' do
expect(subject).to eq(user_verification)
end
end
context 'when a DSLogon user verification is found' do
let(:dslogon_uuid) { 'some-dslogon-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:type) { 'dslogon' }
it 'returns the user verification' do
expect(subject).to eq(user_verification)
end
end
context 'when an MHV user verification is found' do
let(:mhv_uuid) { 'some-mhv-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:type) { 'mhv' }
it 'returns the user verification' do
expect(subject).to eq(user_verification)
end
end
end
end
describe '#verified?' do
subject { user_verification.verified? }
let(:idme_uuid) { 'some-idme-uuid' }
context 'when user_account is verified' do
let(:user_account) { create(:user_account) }
context 'and verified_at is defined' do
let(:verified_at) { Time.zone.now }
it 'returns true' do
expect(subject).to be true
end
end
context 'and verified_at is not defined' do
let(:verified_at) { nil }
it 'returns false' do
expect(subject).to be false
end
end
end
context 'when user_account is not verified' do
let(:user_account) { create(:user_account, icn: nil) }
it 'returns false' do
expect(subject).to be false
end
end
end
describe '#credential_type' do
subject { user_verification.credential_type }
let(:user_account) { create(:user_account) }
context 'when idme_uuid is present' do
let(:idme_uuid) { 'some-idme-uuid' }
let(:expected_credential_type) { SAML::User::IDME_CSID }
it 'returns expected credential type' do
expect(subject).to eq(expected_credential_type)
end
end
context 'when dslogon_uuid is present' do
let(:dslogon_uuid) { 'some-dslogon-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:expected_credential_type) { SAML::User::DSLOGON_CSID }
it 'returns expected credential type' do
expect(subject).to eq(expected_credential_type)
end
end
context 'when mhv_uuid is present' do
let(:mhv_uuid) { 'some-mhv-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:expected_credential_type) { SAML::User::MHV_ORIGINAL_CSID }
it 'returns expected credential type' do
expect(subject).to eq(expected_credential_type)
end
end
context 'when logingov_uuid is present' do
let(:logingov_uuid) { 'some-logingov-uuid' }
let(:expected_credential_type) { SAML::User::LOGINGOV_CSID }
it 'returns expected credential type' do
expect(subject).to eq(expected_credential_type)
end
end
end
describe '#credential_identifier' do
subject { user_verification.credential_identifier }
let(:user_account) { create(:user_account) }
context 'when idme_uuid is present' do
let(:idme_uuid) { 'some-idme-uuid' }
let(:expected_credential_identifier) { idme_uuid }
it 'returns expected credential identifier' do
expect(subject).to eq(expected_credential_identifier)
end
end
context 'when dslogon_uuid is present' do
let(:dslogon_uuid) { 'some-dslogon-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:expected_credential_identifier) { dslogon_uuid }
it 'returns expected credential identifier' do
expect(subject).to eq(expected_credential_identifier)
end
end
context 'when mhv_uuid is present' do
let(:mhv_uuid) { 'some-mhv-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:expected_credential_identifier) { mhv_uuid }
it 'returns expected credential identifier' do
expect(subject).to eq(expected_credential_identifier)
end
end
context 'when logingov_uuid is present' do
let(:logingov_uuid) { 'some-logingov-uuid' }
let(:expected_credential_identifier) { logingov_uuid }
it 'returns expected credential identifier' do
expect(subject).to eq(expected_credential_identifier)
end
end
end
describe '#backing_credential_identifier' do
subject { user_verification.backing_credential_identifier }
let(:user_account) { create(:user_account) }
context 'when logingov_uuid is present' do
let(:logingov_uuid) { 'some-logingov-uuid' }
let(:expected_identifier) { logingov_uuid }
it 'returns logingov_uuid identifier' do
expect(subject).to eq(expected_identifier)
end
end
context 'when logingov_uuid is not present' do
let(:logingov_uuid) { nil }
context 'and idme_uuid is present' do
let(:idme_uuid) { 'some-idme-uuid' }
let(:expected_identifier) { idme_uuid }
it 'returns idme_uuid identifier' do
expect(subject).to eq(expected_identifier)
end
end
context 'and idme_uuid is not present' do
let(:idme_uuid) { nil }
let(:mhv_uuid) { 'some-mhv-uuid' }
let(:backing_idme_uuid) { 'some-backing-idme-uuid' }
let(:expected_identifier) { backing_idme_uuid }
it 'returns backing_idme_uuid identifier' do
expect(subject).to eq(expected_identifier)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_account_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserAccount, type: :model do
let(:user_account) { create(:user_account, icn:) }
let(:icn) { nil }
describe 'validations' do
describe '#icn' do
subject { user_account.icn }
context 'when icn is nil' do
let(:icn) { nil }
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'when icn is unique' do
let(:icn) { 'kitty-icn' }
it 'returns given icn value' do
expect(subject).to eq(icn)
end
end
context 'when icn is not unique' do
let(:icn) { 'kitty-icn' }
let(:expected_error_message) { 'Validation failed: Icn has already been taken' }
before do
create(:user_account, icn:)
end
it 'raises a validation error' do
expect { subject }.to raise_error(ActiveRecord::RecordInvalid, expected_error_message)
end
end
end
end
describe '#verified?' do
subject { user_account.verified? }
context 'when icn is not defined' do
let(:icn) { nil }
it 'returns false' do
expect(subject).to be false
end
end
context 'when icn is defined' do
let(:icn) { 'some-icn-value' }
it 'returns true' do
expect(subject).to be true
end
end
end
describe '#needs_accepted_terms_of_use?' do
subject { user_account.needs_accepted_terms_of_use? }
context 'when icn is not defined' do
let(:icn) { nil }
it 'returns false' do
expect(subject).to be false
end
end
context 'when icn is defined' do
let(:icn) { 'some-icn-value' }
context 'and latest associated terms of use agreement does not exist' do
let(:terms_of_use_agreement) { nil }
it 'is true' do
expect(subject).to be true
end
end
context 'and latest associated terms of use agreement is declined' do
let!(:terms_of_use_agreement) { create(:terms_of_use_agreement, user_account:, response: 'declined') }
it 'is true' do
expect(subject).to be true
end
end
context 'and latest associated terms of use agreement is accepted' do
let!(:terms_of_use_agreement) { create(:terms_of_use_agreement, user_account:, response: 'accepted') }
it 'returns true' do
expect(subject).to be false
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form1095_b_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Form1095B, type: :model do
subject { create(:form1095_b) }
describe 'validations' do
describe '#unique_icn_and_year' do
context 'unique icn + year combo' do
let(:dup) { subject.dup }
it 'requires unique icn and year' do
expect(dup).not_to be_valid
end
it 'allows new years form to be created' do
dup.tax_year = 2020
expect(dup).to be_valid
end
end
context 'form_data validations' do
let(:invalid_form_data) { JSON.parse(subject.form_data) }
let(:invalid_form) { build(:form1095_b, form_data: invalid_form_data.to_json) }
it 'requires a name' do
invalid_form_data['first_name'] = nil
invalid_form = subject.dup
invalid_form.form_data = invalid_form_data.to_json
expect(invalid_form).not_to be_valid
end
end
end
end
describe 'pdf_testing' do
describe 'valid pdf generation' do
it 'generates pdf string for valid 1095_b' do
expect(subject.pdf_file.class).to eq(String)
end
end
describe 'invalid PDF generation' do
let(:inv_year_form) { create(:form1095_b, veteran_icn: '654678976543678', tax_year: 2008) }
it 'fails if no template PDF for the tax_year' do
expect { inv_year_form.pdf_file }.to raise_error(Common::Exceptions::UnprocessableEntity)
end
end
end
describe 'txt_testing' do
describe 'valid text file generation' do
it 'generates text string for valid 1095_b' do
expect(subject.txt_file.class).to eq(String)
end
end
describe 'invalid txt generation' do
let(:inv_year_form) { create(:form1095_b, veteran_icn: '654678976543678', tax_year: 2008) }
it 'fails if no template txt file for the tax_year' 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(subject.txt_file).to include(
'1 Name of responsible individual-First name, middle name, last name ---- John Michael Smith'
)
expect(subject.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
it 'presents name correctly' do
form_data = JSON.parse(subject.form_data)
form_data['middle_name'] = nil
subject.form_data = form_data.to_json
expect(subject.txt_file).to include(
'1 Name of responsible individual-First name, middle name, last name ---- John Smith'
)
expect(subject.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
it 'presents name correctly' do
form_data = JSON.parse(subject.form_data)
form_data['middle_name'] = ''
subject.form_data = form_data.to_json
expect(subject.txt_file).to include(
'1 Name of responsible individual-First name, middle name, last name ---- John Smith'
)
expect(subject.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
|
code_files/vets-api-private/spec/models/veteran_onboarding_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe VeteranOnboarding, type: :model do
let(:user) { build(:user, :loa3) }
let(:user_account) { user.user_account }
describe 'validations' do
it 'validates presence of user_account_uuid' do
subject = described_class.new(user_account: nil)
expect(subject).not_to be_valid
expect(subject.errors.details[:user_account]).to include(error: :blank)
end
it 'validates uniqueness of user_account_uuid' do
described_class.create!(user_account:)
subject = described_class.new(user_account:)
expect(subject).not_to be_valid
expect(subject.errors.details[:user_account]).to include(error: :taken, value: user_account)
end
end
it 'creates a VeteranOnboarding object if toggle is enabled' do
Flipper.enable(:veteran_onboarding_beta_flow, user)
expect { VeteranOnboarding.for_user(user) }.to change(VeteranOnboarding, :count).by(1)
end
describe '#show_onboarding_flow_on_login' do
it 'returns the value of display_onboarding_flow' do
subject = described_class.for_user(user)
Flipper.enable(:veteran_onboarding_beta_flow, user)
expect(subject.show_onboarding_flow_on_login).to be_truthy
end
it 'returns false and updates the database when verification is past the threshold' do
Flipper.enable(:veteran_onboarding_show_to_newly_onboarded, user)
Settings.veteran_onboarding = OpenStruct.new(onboarding_threshold_days: 10)
verified_at_date = Time.zone.today - 11
allow_any_instance_of(UserVerification).to receive(:verified_at).and_return(verified_at_date)
veteran_onboarding = VeteranOnboarding.for_user(user)
expect(veteran_onboarding.show_onboarding_flow_on_login).to be(false)
veteran_onboarding.reload
expect(veteran_onboarding.display_onboarding_flow).to be(false)
end
[
{ days_ago: 10, expected: true },
{ days_ago: 0, expected: true },
{ days_ago: 11, expected: false }
].each do |scenario|
Settings.veteran_onboarding = OpenStruct.new(onboarding_threshold_days: 10)
it "returns #{scenario[:expected]} when verified #{scenario[:days_ago]} days ago" do
verified_at_date = Time.zone.today - scenario[:days_ago]
allow_any_instance_of(UserVerification).to receive(:verified_at).and_return(verified_at_date)
Flipper.enable(:veteran_onboarding_show_to_newly_onboarded, user)
expect(user.onboarding&.show_onboarding_flow_on_login).to eq(scenario[:expected])
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/debt_transaction_log_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DebtTransactionLog, type: :model do
let(:user) { create(:user) }
let(:form5655_submission) { create(:debts_api_form5655_submission, user_uuid: user.uuid) }
let(:digital_dispute_submission) { create(:debts_api_digital_dispute_submission, user_uuid: user.uuid) }
describe 'validations' do
it 'validates required fields' do
log = DebtTransactionLog.new
expect(log).not_to be_valid
expect(log.errors[:transaction_type]).to include("can't be blank")
expect(log.errors[:user_uuid]).to include("can't be blank")
expect(log.errors[:debt_identifiers]).to include("can't be blank")
expect(log.errors[:state]).to include("can't be blank")
end
it 'validates transaction_type inclusion' do
log = build(:debt_transaction_log, transaction_type: 'invalid')
expect(log).not_to be_valid
expect(log.errors[:transaction_type]).to include('is not included in the list')
end
it 'creates a valid transaction log with required attributes' do
log = build(:debt_transaction_log,
transaction_type: 'waiver',
user_uuid: user.uuid,
debt_identifiers: ['debt123'],
state: 'pending',
transactionable: form5655_submission)
expect(log).to be_valid
end
end
describe 'state enum' do
let(:log) { create(:debt_transaction_log, transactionable: form5655_submission) }
it 'has correct state transitions' do
expect(log.pending?).to be true
log.submitted!
expect(log.submitted?).to be true
log.completed!
expect(log.completed?).to be true
end
it 'can transition to failed state' do
log.failed!
expect(log.failed?).to be true
end
end
describe 'polymorphic associations' do
it 'works with Form5655Submission' do
log = create(:debt_transaction_log, transactionable: form5655_submission)
expect(log.transactionable).to eq(form5655_submission)
expect(log.transactionable_type).to eq('DebtsApi::V0::Form5655Submission')
end
it 'works with DigitalDisputeSubmission' do
log = create(:debt_transaction_log,
transactionable_type: 'DebtsApi::V0::DigitalDisputeSubmission',
transactionable_id: digital_dispute_submission.guid)
expect(log.transactionable).to eq(digital_dispute_submission)
expect(log.transactionable_type).to eq('DebtsApi::V0::DigitalDisputeSubmission')
end
end
describe 'class methods' do
it 'delegates track_dispute to service' do
expect(DebtTransactionLogService).to receive(:track_dispute)
.with(digital_dispute_submission, user)
DebtTransactionLog.track_dispute(digital_dispute_submission, user)
end
it 'delegates track_waiver to service' do
expect(DebtTransactionLogService).to receive(:track_waiver)
.with(form5655_submission, user)
DebtTransactionLog.track_waiver(form5655_submission, user)
end
end
describe 'instance methods' do
let(:log) { create(:debt_transaction_log, transactionable: form5655_submission) }
it 'delegates mark_submitted to service' do
expect(DebtTransactionLogService).to receive(:mark_submitted)
.with(transaction_log: log, external_reference_id: 'ref123')
log.mark_submitted(external_reference_id: 'ref123')
end
it 'delegates mark_completed to service' do
expect(DebtTransactionLogService).to receive(:mark_completed)
.with(transaction_log: log, external_reference_id: nil)
log.mark_completed
end
it 'delegates mark_failed to service' do
expect(DebtTransactionLogService).to receive(:mark_failed)
.with(transaction_log: log, external_reference_id: nil)
log.mark_failed
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/education_benefits_claim_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EducationBenefitsClaim, type: :model do
let(:education_benefits_claim) do
create(:va1990).education_benefits_claim
end
%w[1990 1995 5490 5495 0993 0994 10203 10282 10216 10215 10297 1919 0839 10275 8794 0976].each do |form_type|
method = "is_#{form_type}?"
describe "##{method}" do
it "returns false when it's not the right type" do
education_benefits_claim.saved_claim.form_id = 'foo'
expect(education_benefits_claim.public_send(method)).to be(false)
end
it "returns true when it's the right type" do
education_benefits_claim.saved_claim.form_id = "22-#{form_type.upcase}"
expect(education_benefits_claim.public_send(method)).to be(true)
end
end
end
describe '#form_type' do
it 'returns the form type' do
expect(education_benefits_claim.form_type).to eq('1990')
end
end
describe '#regional_office' do
it 'returns the regional office' do
expect(education_benefits_claim.regional_office).to eq(
"VA Regional Office\nP.O. Box 4616\nBuffalo, NY 14240-4616"
)
end
end
describe '#confirmation_number' do
it 'lets you look up a claim from the confirmation number' do
expect(
described_class.find(education_benefits_claim.confirmation_number.gsub('V-EBC-', '').to_i)
).to eq(education_benefits_claim)
end
end
describe 'token' do
it 'automatically generates a unique token' do
expect(education_benefits_claim.token).not_to be_nil
end
end
describe '#update_education_benefits_submission_status' do
subject do
education_benefits_claim.update!(processed_at: Time.zone.now)
education_benefits_claim
end
it 'updates the education_benefits_submission status' do
expect(subject.education_benefits_submission.status).to eq('processed')
end
context 'when the education_benefits_submission is missing' do
before do
education_benefits_claim.education_benefits_submission.destroy
education_benefits_claim.reload
end
it 'the callback shouldnt raise error' do
subject
end
end
end
describe '#create_education_benefits_submission' do
subject { create(:va1990_western_region) }
let(:submission_attributes) do
{
'region' => 'eastern',
'chapter33' => false,
'chapter30' => false,
'chapter1606' => false,
'chapter32' => false,
'chapter35' => false,
'status' => 'submitted',
'transfer_of_entitlement' => false,
'chapter1607' => false,
'vettec' => false,
'vrrap' => false,
'education_benefits_claim_id' => subject.education_benefits_claim.id
}
end
def associated_submission
subject.education_benefits_claim.education_benefits_submission.attributes.except('id', 'created_at', 'updated_at')
end
it 'creates an education benefits submission after submission' do
expect do
subject
end.to change(EducationBenefitsSubmission, :count).by(1)
expect(associated_submission).to eq(
submission_attributes.merge(
'region' => 'western',
'chapter1606' => true,
'form_type' => '1990'
)
)
end
context 'with a form type of 1995 and benefit transfer of entitlement' do
subject do
create(:va1995)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '1995',
'transfer_of_entitlement' => true
)
)
end
end
context 'with a form type of 1995 and benefit chapter33 post911' do
subject do
create(:va1995_ch33_post911)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '1995',
'chapter33' => true
)
)
end
end
context 'with a form type of 1995 and benefit chapter33 fry scholarship' do
subject do
create(:va1995_ch33_fry)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '1995',
'chapter33' => true
)
)
end
end
context 'with a form type of 5490' do
subject do
create(:va5490)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'chapter35' => true,
'form_type' => '5490'
)
)
end
end
context 'with a form type of 5495' do
subject do
create(:va5495)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '5495',
'chapter35' => true
)
)
end
end
context 'with a form type of 10203' do
subject do
create(:va10203)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '10203',
'transfer_of_entitlement' => true
)
)
end
end
context 'with a form type of 10282' do
subject do
create(:va10282)
end
it 'creates a submission' do
subject
expect(associated_submission).to eq(
submission_attributes.merge(
'form_type' => '10282'
)
)
end
end
it 'does not create a submission after save if it was already submitted' do
subject.education_benefits_claim.update!(processed_at: Time.zone.now)
expect(EducationBenefitsSubmission.count).to eq(1)
end
end
describe '#copy_from_previous_benefits' do
subject do
saved_claim = build(:va1990, form: form.to_json)
education_benefits_claim.instance_variable_set(:@application, saved_claim.open_struct_form)
education_benefits_claim.copy_from_previous_benefits
education_benefits_claim.open_struct_form
end
let(:form) do
{
previousBenefits: {
veteranFullName: 'joe',
vaFileNumber: '123',
veteranSocialSecurityNumber: '321'
}
}
end
context 'when currentSameAsPrevious is false' do
before do
form[:currentSameAsPrevious] = false
end
it 'shouldnt copy fields from previous benefits' do
%w[veteranFullName vaFileNumber veteranSocialSecurityNumber].each do |attr|
expect(subject.public_send(attr)).to be_nil
end
end
end
context 'when currentSameAsPrevious is true' do
before do
form[:currentSameAsPrevious] = true
end
it 'copies fields from previous benefits' do
expect(subject.veteranFullName).to eq('joe')
expect(subject.vaFileNumber).to eq('123')
expect(subject.veteranSocialSecurityNumber).to eq('321')
end
end
end
describe 'reprocess_at' do
it 'raises an error if an invalid region is entered' do
expect { education_benefits_claim.reprocess_at('nowhere') }.to raise_error(/Invalid region/)
end
it 'sets a record for processing' do
expect do
education_benefits_claim.reprocess_at('western')
end.to change(education_benefits_claim, :regional_processing_office).from('eastern').to('western')
expect(education_benefits_claim.processed_at).to be_nil
end
end
describe '#form_headers' do
it 'appends 22- to FORM_TYPES' do
expect(described_class.form_headers).to eq(described_class::FORM_TYPES.map { |t| "22-#{t}" }.freeze)
end
it 'appends 22- to passed in array' do
form_types = %w[10203]
form_headers = %w[22-10203]
expect(described_class.form_headers(form_types)).to eq(form_headers)
end
end
describe '#region' do
it 'returns the region for the claim' do
expect(education_benefits_claim.region).to be_a(Symbol)
expect(EducationForm::EducationFacility::REGIONS).to include(education_benefits_claim.region)
end
end
describe '#unprocessed' do
it 'returns claims without processed_at' do
processed = create(:va1990).education_benefits_claim
processed.update!(processed_at: Time.zone.now)
unprocessed1 = create(:va1990).education_benefits_claim
unprocessed2 = create(:va1995).education_benefits_claim
expect(described_class.unprocessed).to include(unprocessed1, unprocessed2)
expect(described_class.unprocessed).not_to include(processed)
end
end
describe '#set_region' do
it 'sets regional_processing_office if not already set' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
claim.regional_processing_office = nil
claim.save!
expect(claim.regional_processing_office).not_to be_nil
expect(claim.regional_processing_office).to eq(claim.region.to_s)
end
it 'does not override existing regional_processing_office' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
claim.regional_processing_office = 'custom_region'
claim.save!
expect(claim.regional_processing_office).to eq('custom_region')
end
end
describe '#open_struct_form' do
it 'returns an OpenStruct with confirmation number' do
result = education_benefits_claim.open_struct_form
expect(result).to be_a(OpenStruct)
expect(result.confirmation_number).to match(/^V-EBC-/)
end
it 'memoizes the result' do
result1 = education_benefits_claim.open_struct_form
result2 = education_benefits_claim.open_struct_form
expect(result1.object_id).to eq(result2.object_id)
end
context 'with form type 1990' do
it 'transforms the form correctly' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
result = claim.open_struct_form
expect(result.confirmation_number).to match(/^V-EBC-/)
end
end
end
describe '#transform_form' do
context 'with form type 1990' do
it 'calls generate_benefits_to_apply_to' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
claim.open_struct_form
tours = claim.instance_variable_get(:@application).toursOfDuty
if tours&.any?
tour_with_selected = tours.find(&:applyPeriodToSelected)
expect(tour_with_selected&.benefitsToApplyTo).to be_present if tour_with_selected
end
end
end
context 'with form type 5490' do
it 'calls copy_from_previous_benefits when currentSameAsPrevious is true' do
saved_claim = create(:va5490)
claim = saved_claim.education_benefits_claim
result = claim.open_struct_form
expect(result).to be_a(OpenStruct)
end
end
end
describe '#generate_benefits_to_apply_to' do
it 'generates benefits string for tours with applyPeriodToSelected' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
claim.open_struct_form
tours = claim.instance_variable_get(:@application).toursOfDuty
if tours&.any?
tour_with_selected = tours.find(&:applyPeriodToSelected)
expect(tour_with_selected&.benefitsToApplyTo).to be_present if tour_with_selected
end
end
end
describe '#selected_benefits' do
context 'with form type 1990' do
it 'returns all application types from parsed_form' do
saved_claim = create(:va1990)
claim = saved_claim.education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to be_a(Hash)
expect(benefits.keys).to be_a(Array)
end
end
context 'with form type 0994' do
it 'returns vettec benefit' do
claim = create(:va0994_minimum_form).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits['vettec']).to be(true)
end
end
context 'with form type 10297' do
it 'returns vettec benefit' do
claim = create(:va10297_simple_form).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits['vettec']).to be(true)
end
end
context 'with form type 1995' do
context 'with chapter33 post911 benefit' do
it 'returns chapter33 benefit' do
claim = create(:va1995_ch33_post911).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits['chapter33']).to be(true)
end
end
context 'with chapter33 fry scholarship benefit' do
it 'returns chapter33 benefit' do
claim = create(:va1995_ch33_fry).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits['chapter33']).to be(true)
end
end
context 'with transfer of entitlement benefit' do
it 'returns transfer_of_entitlement benefit' do
claim = create(:va1995).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits['transfer_of_entitlement']).to be(true)
end
end
context 'with other benefit' do
it 'returns the benefit' do
saved_claim = create(:va1995)
claim = saved_claim.education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to be_a(Hash)
end
end
end
context 'with form type 5490' do
it 'returns the benefit' do
saved_claim = create(:va5490)
claim = saved_claim.education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to be_a(Hash)
end
end
context 'with form type 5495' do
it 'returns the benefit' do
saved_claim = create(:va5495)
claim = saved_claim.education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to be_a(Hash)
end
end
context 'with form type 10203' do
it 'returns the benefit' do
saved_claim = create(:va10203)
claim = saved_claim.education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to be_a(Hash)
end
end
context 'with form type without benefit field' do
it 'returns empty hash' do
claim = create(:va10282).education_benefits_claim
benefits = claim.selected_benefits
expect(benefits).to eq({})
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/folder_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Folder do
describe 'validations on name' do
subject { described_class.new(params) }
before { subject.valid? }
context 'with name set to nil' do
let(:params) { { name: nil } }
it 'has errors for presence of name' do
expect(subject.errors[:name].first).to eq('can\'t be blank')
end
end
context 'with name exceeding 50 characters' do
let(:params) { { name: 'a' * 51 } }
it 'has errors for length of name exceeding 50' do
expect(subject.errors[:name].first).to eq('is too long (maximum is 50 characters)')
end
end
context 'with name having non alphanumeric characters' do
let(:params) { { name: 'name!' } }
it 'has errors for not being alphanumeric' do
expect(subject.errors[:name].first).to eq('is not alphanumeric (letters, numbers, or spaces)')
end
end
context 'with name having control characters' do
let(:params) { { name: "name \n name" } }
it 'has errors for illegal characters' do
expect(subject.errors[:name].first).to eq('contains illegal characters')
end
end
end
context 'with valid attributes' do
subject { described_class.new(params) }
let(:params) { attributes_for(:folder, id: 0) }
let(:other) { described_class.new(attributes_for(:folder, id: 1)) }
it 'populates attributes' do
expect(described_class.attribute_set).to contain_exactly(:id, :name, :count, :unread_count,
:system_folder, :metadata)
expect(subject.id).to eq(params[:id])
expect(subject.name).to eq(params[:name])
expect(subject.count).to eq(params[:count])
expect(subject.unread_count).to eq(params[:unread_count])
expect(subject.system_folder).to eq(params[:system_folder])
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/gi_bill_feedback_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe GIBillFeedback, type: :model do
let(:gi_bill_feedback) { build(:gi_bill_feedback) }
describe '#find' do
it 'is able to find created models' do
gi_bill_feedback.save!
guid = gi_bill_feedback.guid
expect(described_class.find(guid).guid).to eq(guid)
end
end
describe '#remove_malformed_options' do
it 'removes malformed options' do
expect(gi_bill_feedback.send(:remove_malformed_options,
'Post-9/11 Ch 33' => true,
'post9::11 ch 33' => true,
'MGIB-AD Ch 30' => true)).to eq(
'Post-9/11 Ch 33' => true, 'MGIB-AD Ch 30' => true
)
end
end
describe '#transform_malformed_options' do
it 'transforms malformed options' do
expect(gi_bill_feedback.send(:transform_malformed_options,
'post9::11 ch 33' => true,
'MGIB-AD Ch 30' => true,
'chapter1606' => true)).to eq(
'Post-9/11 Ch 33' => true, 'MGIB-AD Ch 30' => true,
'MGIB-SR Ch 1606' => true
)
end
end
describe '#transform_form' do
before do
gi_bill_feedback.user = user
end
context 'with no user' do
let(:user) { nil }
it 'transforms the form' do
form = gi_bill_feedback.parsed_form
gi_bill_feedback.form = form.to_json
gi_bill_feedback.send(:remove_instance_variable, :@parsed_form)
expect(gi_bill_feedback.transform_form).to eq(get_fixture('gibft/transform_form_no_user'))
end
end
context 'with a user' do
let(:user) { create(:user, :legacy_icn) }
it 'transforms the form to the right format' do
expect(gi_bill_feedback.transform_form).to eq(get_fixture('gibft/transform_form'))
end
context 'with malformed options' do
before do
form = gi_bill_feedback.parsed_form
form['educationDetails']['programs'] = {
'mGIBAd ch 30' => true
}
gi_bill_feedback.form = form.to_json
gi_bill_feedback.send(:remove_instance_variable, :@parsed_form)
end
it 'transforms the malformed options' do
expect(gi_bill_feedback.transform_form).to eq(get_fixture('gibft/transform_form'))
end
end
end
end
describe '#create_submission_job' do
it 'does not pass in the user if form is anonymous' do
form = gi_bill_feedback.parsed_form
form['onBehalfOf'] = 'Anonymous'
user = create(:user)
gi_bill_feedback.form = form.to_json
gi_bill_feedback.instance_variable_set(:@parsed_form, nil)
gi_bill_feedback.user = user
expect(GIBillFeedbackSubmissionJob).to receive(:perform_async).with(gi_bill_feedback.id, form.to_json, nil)
gi_bill_feedback.send(:create_submission_job)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form_attachment_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormAttachment do
let(:preneed_attachment) { build(:preneed_attachment) }
describe '#set_file_data!' do
it 'stores the file and set the file_data' do
expect(preneed_attachment.parsed_file_data['filename']).to eq('extras.pdf')
end
describe '#unlock_pdf' do
let(:file_name) { 'locked_pdf_password_is_test.Pdf' }
let(:bad_password) { 'bad_pw' }
context 'when provided password is incorrect' do
it 'logs a sanitized message to Sentry and Rails' do
error_message = nil
allow_any_instance_of(FormAttachment).to receive(:log_message_to_sentry) do |_, message, _level|
error_message = message
end
allow(Rails.logger).to receive(:warn)
tempfile = Tempfile.new(['', "-#{file_name}"])
file = ActionDispatch::Http::UploadedFile.new(original_filename: file_name, type: 'application/pdf',
tempfile:)
expect do
preneed_attachment.set_file_data!(file, bad_password)
end.to raise_error(Common::Exceptions::UnprocessableEntity)
expect(error_message).not_to include(file_name)
expect(error_message).not_to include(bad_password)
expect(Rails.logger).to have_received(:warn)
end
end
end
end
describe '#get_file' do
it 'gets the file from storage' do
preneed_attachment.save!
preneed_attachment2 = Preneeds::PreneedAttachment.find(preneed_attachment.id)
file = preneed_attachment2.get_file
expect(file.exists?).to be(true)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/mhv_opt_in_flag_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe MHVOptInFlag do
subject { described_class.new(params) }
let(:params) { { user_account_id: account_uuid, feature: } }
let(:user_verification) { create(:user_verification) }
let(:user_account) { user_verification.user_account }
let(:account_uuid) { user_account.id }
let(:feature) { 'secure_messaging' }
it 'populates passed-in attributes' do
expect(subject.user_account_id).to eq(account_uuid)
expect(subject.feature).to eq(feature)
end
it 'has a foreign key to an associated user account' do
associated_account = UserAccount.find(subject.user_account_id)
expect(associated_account).not_to be_nil
expect(associated_account.id).to eq(account_uuid)
end
describe 'validation' do
context 'feature included in FEATURES constant' do
it 'accepts features included in the FEATURES constant' do
expect(subject).to be_valid
end
end
context 'feature not included in FEATURES constant' do
let(:feature) { 'invalid_feature_flag' }
it 'rejects features no included in the FEATURES constant' do
expect(subject).not_to be_valid
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/accredited_individual_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe AccreditedIndividual, type: :model do
describe 'validations' do
subject { build(:accredited_individual) }
it { is_expected.to have_many(:accredited_organizations).through(:accreditations) }
it { expect(subject).to validate_presence_of(:ogc_id) }
it { expect(subject).to validate_presence_of(:registration_number) }
it { expect(subject).to validate_presence_of(:individual_type) }
it { expect(subject).to validate_length_of(:poa_code).is_equal_to(3).allow_blank }
it {
expect(subject).to validate_uniqueness_of(:individual_type)
.scoped_to(:registration_number)
.ignoring_case_sensitivity
}
it {
expect(subject).to define_enum_for(:individual_type)
.with_values({
'attorney' => 'attorney',
'claims_agent' => 'claims_agent',
'representative' => 'representative'
})
.backed_by_column_of_type(:string)
}
end
describe '.find_within_max_distance' do
# ~6 miles from Washington, D.C.
let!(:ai1) do
create(:accredited_individual, registration_number: '12300', long: -77.050552, lat: 38.820450,
location: 'POINT(-77.050552 38.820450)')
end
# ~35 miles from Washington, D.C.
let!(:ai2) do
create(:accredited_individual, registration_number: '23400', long: -76.609383, lat: 39.299236,
location: 'POINT(-76.609383 39.299236)')
end
# ~47 miles from Washington, D.C.
let!(:ai3) do
create(:accredited_individual, registration_number: '34500', long: -77.466316, lat: 38.309875,
location: 'POINT(-77.466316 38.309875)')
end
# ~57 miles from Washington, D.C.
let!(:ai4) do
create(:accredited_individual, registration_number: '45600', long: -76.3483, lat: 39.5359,
location: 'POINT(-76.3483 39.5359)')
end
context 'when there are individuals within the max search distance' do
it 'returns all individuals located within the default max distance' do
# check within 50 miles of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072)
expect(results.pluck(:id)).to contain_exactly(ai1.id, ai2.id, ai3.id)
end
it 'returns all individuals located within the specified max distance' do
# check within 40 miles of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072, 64_373.8)
expect(results.pluck(:id)).to contain_exactly(ai1.id, ai2.id)
end
end
context 'when there are no individuals within the max search distance' do
it 'returns an empty array' do
# check within 1 mile of Washington, D.C.
results = described_class.find_within_max_distance(-77.0369, 38.9072, 1609.344)
expect(results).to eq([])
end
end
end
describe '.find_with_full_name_similar_to' do
before do
# word similarity to Bob Law value = 1
create(:accredited_individual, registration_number: '12300', first_name: 'Bob', last_name: 'Law')
# word similarity to Bob Law value = 0.375
create(:accredited_individual, registration_number: '23400', first_name: 'Bobby', last_name: 'Low')
# word similarity to Bob Law value = 0.375
create(:accredited_individual, registration_number: '34500', first_name: 'Bobbie', last_name: 'Lew')
# word similarity to Bob Law value = 0.25
create(:accredited_individual, registration_number: '45600', first_name: 'Robert', last_name: 'Lanyard')
end
context 'when there are accredited individuals with full names similar to the search phrase' do
it 'returns all individuals with full names >= the word similarity threshold' do
results = described_class.find_with_full_name_similar_to('Bob Law', 0.3)
expect(results.pluck(:registration_number)).to match_array(%w[12300 23400 34500])
end
end
context 'when there are no accredited individuals with full names similar to the search phrase' do
it 'returns an empty array' do
results = described_class.find_with_full_name_similar_to('No Name')
expect(results.pluck(:registration_number)).to eq([])
end
end
end
describe '#poa_codes' do
context 'when the individual has no poa code' do
let(:individual) { create(:accredited_individual) }
context 'when the individual has no accredited_organization associations' do
it 'returns an empty array' do
expect(individual.poa_codes).to eq([])
end
end
context 'when the individual has accredited_organization associations' do
let(:org1) { create(:accredited_organization, poa_code: 'ABC') }
let(:org2) { create(:accredited_organization, poa_code: 'DEF') }
it 'returns an array of the associated accredited_organizations poa_codes' do
individual.accredited_organizations.push(org1, org2)
expect(individual.reload.poa_codes).to match_array(%w[ABC DEF])
end
end
end
context 'when the individual has a poa code' do
let(:individual) { create(:accredited_individual, individual_type: 'attorney', poa_code: 'A12') }
context 'when the individual has no accredited_organization associations' do
it 'returns an array of only the individual poa_code' do
expect(individual.poa_codes).to eq(['A12'])
end
end
context 'when the individual has accredited_organization associations' do
let(:org1) { create(:accredited_organization, poa_code: 'ABC') }
let(:org2) { create(:accredited_organization, poa_code: 'DEF') }
it 'returns an array of all associated poa_codes' do
individual.accredited_organizations.push(org1, org2)
expect(individual.reload.poa_codes).to match_array(%w[ABC DEF A12])
end
end
end
end
describe '#set_full_name' do
subject { build(:accredited_individual, first_name:, last_name:) }
context 'when both first_name and last_name are present' do
let(:first_name) { 'John' }
let(:last_name) { 'Doe' }
it 'sets full_name to "first_name last_name"' do
subject.save
expect(subject.full_name).to eq('John Doe')
end
end
context 'when only first_name is present' do
let(:first_name) { 'John' }
let(:last_name) { nil }
it 'sets full_name to first_name only' do
subject.save
expect(subject.full_name).to eq('John')
end
end
context 'when only last_name is present' do
let(:first_name) { nil }
let(:last_name) { 'Doe' }
it 'sets full_name to last_name only' do
subject.save
expect(subject.full_name).to eq('Doe')
end
end
context 'when both first_name and last_name are blank' do
let(:first_name) { nil }
let(:last_name) { nil }
it 'sets full_name to empty string' do
subject.save
expect(subject.full_name).to eq('')
end
end
context 'when first_name is empty string and last_name is present' do
let(:first_name) { '' }
let(:last_name) { 'Doe' }
it 'sets full_name to last_name only' do
subject.save
expect(subject.full_name).to eq('Doe')
end
end
context 'when last_name is empty string and first_name is present' do
let(:first_name) { 'John' }
let(:last_name) { '' }
it 'sets full_name to first_name only' do
subject.save
expect(subject.full_name).to eq('John')
end
end
context 'when both first_name and last_name are empty strings' do
let(:first_name) { '' }
let(:last_name) { '' }
it 'sets full_name to empty string' do
subject.save
expect(subject.full_name).to eq('')
end
end
context 'when names contain whitespace' do
let(:first_name) { ' John ' }
let(:last_name) { ' Doe ' }
it 'removes whitespace in full_name' do
subject.save
expect(subject.full_name).to eq('John Doe')
end
end
context 'when names contain special characters' do
let(:first_name) { "O'Connor" }
let(:last_name) { 'Smith-Johnson' }
it 'preserves special characters in full_name' do
subject.save
expect(subject.full_name).to eq("O'Connor Smith-Johnson")
end
end
context 'when updating an existing record' do
let(:individual) { create(:accredited_individual, first_name: 'Jane', last_name: 'Smith') }
it 'updates full_name when first_name changes' do
individual.update(first_name: 'Janet')
expect(individual.full_name).to eq('Janet Smith')
end
it 'updates full_name when last_name changes' do
individual.update(last_name: 'Jones')
expect(individual.full_name).to eq('Jane Jones')
end
it 'updates full_name when both names change' do
individual.update(first_name: 'Bob', last_name: 'Wilson')
expect(individual.full_name).to eq('Bob Wilson')
end
it 'updates full_name when first_name is set to nil' do
individual.update(first_name: nil)
expect(individual.full_name).to eq('Smith')
end
it 'updates full_name when last_name is set to nil' do
individual.update(last_name: nil)
expect(individual.full_name).to eq('Jane')
end
end
context 'when manually calling set_full_name' do
let(:individual) { build(:accredited_individual, first_name: 'Test', last_name: 'User') }
it 'updates full_name without saving' do
individual.first_name = 'Updated'
individual.set_full_name
expect(individual.full_name).to eq('Updated User')
expect(individual.changed?).to be true
end
end
end
describe 'full_name attribute' do
context 'when creating a new record' do
it 'is automatically set via before_save callback' do
individual = create(:accredited_individual, first_name: 'Auto', last_name: 'Generated')
expect(individual.full_name).to eq('Auto Generated')
end
end
context 'when full_name is manually set' do
let(:individual) { build(:accredited_individual, first_name: 'John', last_name: 'Doe') }
it 'is overwritten by before_save callback' do
individual.full_name = 'Manual Name'
individual.save
expect(individual.full_name).to eq('John Doe')
end
end
context 'when used in database queries' do
before do
create(:accredited_individual, first_name: 'Alice', last_name: 'Johnson')
create(:accredited_individual, first_name: 'Bob', last_name: 'Smith')
create(:accredited_individual, first_name: 'Charlie', last_name: nil)
end
it 'can be searched by full_name' do
results = described_class.where(full_name: 'Alice Johnson')
expect(results.count).to eq(1)
expect(results.first.first_name).to eq('Alice')
end
it 'can be ordered by full_name' do
results = described_class.order(:full_name)
expect(results.pluck(:full_name)).to eq(['Alice Johnson', 'Bob Smith', 'Charlie'])
end
end
end
describe '#validate_address' do
let(:raw_address_data) do
{
'address_line1' => '123 Main St',
'address_line2' => 'Suite 100',
'city' => 'Brooklyn',
'state_code' => 'NY',
'zip_code' => '11249'
}
end
let(:validated_attributes) do
{
address_line1: '123 Main St',
address_line2: 'Suite 100',
city: 'Brooklyn',
state_code: 'NY',
zip_code: '11249',
lat: 40.717029,
long: -73.964956,
location: 'POINT(-73.964956 40.717029)'
}
end
let(:mock_service) { instance_double(RepresentationManagement::AddressValidationService) }
context 'with valid raw_address' do
let(:individual) { create(:accredited_individual, raw_address: raw_address_data) }
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).with(raw_address_data).and_return(validated_attributes)
end
it 'delegates to the validation service' do
expect(RepresentationManagement::AddressValidationService).to receive(:new)
expect(mock_service).to receive(:validate_address).with(raw_address_data)
individual.validate_address
end
it 'saves validated attributes to the record' do
expect(individual.validate_address).to be true
individual.reload
expect(individual.address_line1).to eq('123 Main St')
expect(individual.city).to eq('Brooklyn')
expect(individual.state_code).to eq('NY')
expect(individual.lat).to eq(40.717029)
expect(individual.long).to eq(-73.964956)
end
it 'returns true when validation succeeds' do
expect(individual.validate_address).to be true
end
end
context 'with blank raw_address' do
let(:individual) { create(:accredited_individual, raw_address: nil) }
it 'skips validation service' do
expect(RepresentationManagement::AddressValidationService).not_to receive(:new)
expect(individual.validate_address).to be false
end
it 'leaves the record unchanged' do
original_address = individual.address_line1
individual.validate_address
expect(individual.reload.address_line1).to eq(original_address)
end
end
context 'with empty hash raw_address' do
let(:individual) { create(:accredited_individual, raw_address: {}) }
it 'bails out early' do
expect(RepresentationManagement::AddressValidationService).not_to receive(:new)
expect(individual.validate_address).to be false
end
end
context 'when validation service returns nil' do
let(:individual) { create(:accredited_individual, raw_address: raw_address_data) }
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).and_return(nil)
end
it 'handles failed validation gracefully' do
expect(individual.validate_address).to be false
end
it 'keeps original address intact' do
original_address = individual.address_line1
individual.validate_address
expect(individual.reload.address_line1).to eq(original_address)
end
end
context 'when validation service raises an error' do
let(:individual) { create(:accredited_individual, raw_address: raw_address_data) }
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).and_raise(StandardError.new('Service error'))
end
it 'catches and logs the error' do
expect(Rails.logger).to receive(:error).with(/Address validation failed for AccreditedIndividual/)
individual.validate_address
end
it 'returns false on exception' do
allow(Rails.logger).to receive(:error)
expect(individual.validate_address).to be false
end
it 'rolls back changes' do
allow(Rails.logger).to receive(:error)
original_address = individual.address_line1
individual.validate_address
expect(individual.reload.address_line1).to eq(original_address)
end
end
context 'when update fails' do
let(:individual) { create(:accredited_individual, raw_address: raw_address_data) }
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).and_return(validated_attributes)
allow(individual).to receive(:update).and_return(false)
end
it 'returns false when update fails' do
expect(individual.validate_address).to be false
end
end
context 'idempotency' do
let(:individual) { create(:accredited_individual, raw_address: raw_address_data) }
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).with(raw_address_data).and_return(validated_attributes)
end
it 'handles repeated calls without issues' do
expect(individual.validate_address).to be true
first_lat = individual.reload.lat
expect(individual.validate_address).to be true
second_lat = individual.reload.lat
expect(first_lat).to eq(second_lat)
end
end
context 'with different individual types' do
before do
allow(RepresentationManagement::AddressValidationService).to receive(:new).and_return(mock_service)
allow(mock_service).to receive(:validate_address).and_return(validated_attributes)
end
it 'validates attorneys' do
attorney = create(:accredited_individual, :attorney, raw_address: raw_address_data)
expect(attorney.validate_address).to be true
end
it 'validates claims agents' do
agent = create(:accredited_individual, :claims_agent, raw_address: raw_address_data)
expect(agent.validate_address).to be true
end
it 'validates representatives' do
rep = create(:accredited_individual, :representative, raw_address: raw_address_data)
expect(rep.validate_address).to be true
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/disability_contention_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DisabilityContention, type: :model do
describe '.suggested' do
before do
create(:disability_contention_arrhythmia)
create(:disability_contention_arteriosclerosis)
create(:disability_contention_arthritis)
end
it 'finds records that only match the medical term' do
expect(DisabilityContention.suggested('ar').count).to eq(3)
end
it 'refines records that only match the medical term' do
expect(DisabilityContention.suggested('arte').count).to eq(1)
end
it 'finds records that only match the lay term' do
expect(DisabilityContention.suggested('joint').count).to eq(1)
end
it 'find records that match both medical and lay terms' do
expect(DisabilityContention.suggested('art').count).to eq(3)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/mhv_metrics_unique_user_event_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe MHVMetricsUniqueUserEvent, type: :model do
let(:user_id) { SecureRandom.uuid }
let(:event_name) { 'test_event' }
let(:cache_key) { "#{user_id}:#{event_name}" }
# Test data setup
let(:valid_attributes) do
{
user_id:,
event_name:
}
end
describe 'validations' do
it 'validates presence of user_id' do
record = described_class.new(valid_attributes.except(:user_id))
expect(record).not_to be_valid
expect(record.errors[:user_id]).to include("can't be blank")
end
it 'validates presence of event_name' do
record = described_class.new(valid_attributes.except(:event_name))
expect(record).not_to be_valid
expect(record.errors[:event_name]).to include("can't be blank")
end
it 'validates event_name length maximum of 50 characters' do
long_event_name = 'a' * 51
record = described_class.new(valid_attributes.merge(event_name: long_event_name))
expect(record).not_to be_valid
expect(record.errors[:event_name]).to include('is too long (maximum is 50 characters)')
end
it 'allows event_name with exactly 50 characters' do
event_name = 'a' * 50
record = described_class.new(valid_attributes.merge(event_name:))
expect(record).to be_valid
end
it 'is valid with valid attributes' do
record = described_class.new(valid_attributes)
expect(record).to be_valid
end
end
describe '.event_exists?' do
context 'with invalid parameters' do
it 'raises ArgumentError when user_id is blank' do
expect do
described_class.event_exists?(user_id: '', event_name:)
end.to raise_error(ArgumentError, 'user_id is required')
end
it 'raises ArgumentError when user_id is nil' do
expect do
described_class.event_exists?(user_id: nil, event_name:)
end.to raise_error(ArgumentError, 'user_id is required')
end
it 'raises ArgumentError when event_name is blank' do
expect do
described_class.event_exists?(user_id:, event_name: '')
end.to raise_error(ArgumentError, 'event_name is required')
end
it 'raises ArgumentError when event_name is too long' do
long_event_name = 'a' * 51
expect do
described_class.event_exists?(user_id:, event_name: long_event_name)
end.to raise_error(ArgumentError, 'event_name must be 50 characters or less')
end
end
context 'with valid parameters' do
before do
allow(described_class).to receive(:key_cached?)
allow(described_class).to receive(:mark_key_cached)
allow(described_class).to receive(:exists?)
end
it 'returns true when event exists in cache' do
allow(described_class).to receive(:key_cached?).with(cache_key).and_return(true)
result = described_class.event_exists?(user_id:, event_name:)
expect(result).to be(true)
expect(described_class).not_to have_received(:exists?)
end
it 'checks database when not in cache and caches result when found' do
allow(described_class).to receive(:key_cached?).with(cache_key).and_return(false)
allow(described_class).to receive(:exists?).with(user_id:, event_name:).and_return(true)
result = described_class.event_exists?(user_id:, event_name:)
expect(result).to be(true)
expect(described_class).to have_received(:exists?).with(user_id:, event_name:)
expect(described_class).to have_received(:mark_key_cached).with(cache_key)
end
it 'returns false when event does not exist and does not cache negative result' do
allow(described_class).to receive(:key_cached?).with(cache_key).and_return(false)
allow(described_class).to receive(:exists?).with(user_id:, event_name:).and_return(false)
result = described_class.event_exists?(user_id:, event_name:)
expect(result).to be(false)
expect(described_class).not_to have_received(:mark_key_cached)
end
end
end
describe '.record_event' do
before do
allow(Rails.logger).to receive(:info)
allow(Rails.logger).to receive(:debug)
allow(described_class).to receive(:key_cached?)
allow(described_class).to receive(:mark_key_cached)
end
context 'with invalid parameters' do
it 'raises ArgumentError when user_id is blank' do
expect do
described_class.record_event(user_id: '', event_name:)
end.to raise_error(ArgumentError, 'user_id is required')
end
it 'raises ArgumentError when event_name is blank' do
expect do
described_class.record_event(user_id:, event_name: '')
end.to raise_error(ArgumentError, 'event_name is required')
end
end
context 'when event exists in cache' do
before do
allow(described_class).to receive(:key_cached?).with(cache_key).and_return(true)
allow(Rails.logger).to receive(:debug)
end
it 'returns false without attempting database operation' do
result = described_class.record_event(user_id:, event_name:)
expect(result).to be(false)
expect(Rails.logger).to have_received(:debug)
.with('UUM: Event found in cache', { user_id:, event_name: })
end
end
context 'when event does not exist in cache' do
before do
allow(described_class).to receive(:key_cached?).with(cache_key).and_return(false)
end
context 'and record is successfully created' do
let(:insert_result) { double('InsertResult', rows: [[user_id, event_name]]) }
before do
allow(described_class).to receive(:insert)
.with(
{ user_id:, event_name: },
unique_by: %i[user_id event_name],
returning: %i[user_id event_name]
)
.and_return(insert_result)
end
it 'returns true and logs success' do
result = described_class.record_event(user_id:, event_name:)
expect(result).to be(true)
expect(described_class).to have_received(:insert)
.with(
{ user_id:, event_name: },
unique_by: %i[user_id event_name],
returning: %i[user_id event_name]
)
expect(described_class).to have_received(:mark_key_cached).with(cache_key)
expect(Rails.logger).to have_received(:debug)
.with('UUM: New unique event recorded', { user_id:, event_name: })
end
end
context 'and record already exists in database' do
let(:insert_result) { double('InsertResult', rows: []) }
before do
allow(described_class).to receive(:insert)
.with(
{ user_id:, event_name: },
unique_by: %i[user_id event_name],
returning: %i[user_id event_name]
)
.and_return(insert_result)
allow(Rails.logger).to receive(:debug)
end
it 'returns false and logs debug message' do
result = described_class.record_event(user_id:, event_name:)
expect(result).to be(false)
expect(described_class).to have_received(:mark_key_cached).with(cache_key)
expect(Rails.logger).to have_received(:debug)
.with('UUM: Duplicate event found in database', { user_id:, event_name: })
end
end
end
context 'integration test with real database' do
let(:test_user_id) { SecureRandom.uuid }
let(:test_event_name) { 'integration_test_event' }
before do
# Ensure cache is clear for this specific key
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
end
after do
# Cleanup test data and cache
described_class.where(user_id: test_user_id).delete_all
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
end
it 'returns correct values for new vs duplicate inserts' do
# First insert with cache clear - should return true (new event)
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
result1 = described_class.record_event(user_id: test_user_id, event_name: test_event_name)
expect(result1).to be(true), 'First insert should return true for new event'
# Second insert with cache clear - should return false (duplicate)
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
result2 = described_class.record_event(user_id: test_user_id, event_name: test_event_name)
expect(result2).to be(false), 'Duplicate insert should return false'
# Subsequent inserts should also return false
3.times do
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
result = described_class.record_event(user_id: test_user_id, event_name: test_event_name)
expect(result).to be(false), 'Multiple duplicate inserts should all return false'
end
# Verify only one record exists (INSERT ON CONFLICT prevented duplicates)
records = described_class.where(user_id: test_user_id, event_name: test_event_name)
expect(records.count).to eq(1)
expect(records.first.created_at).to be_present
end
it 'does not raise exceptions on duplicate inserts' do
# Verify no ActiveRecord::RecordNotUnique exceptions are raised
expect do
5.times do
Rails.cache.delete("#{test_user_id}:#{test_event_name}", namespace: 'unique_user_metrics')
described_class.record_event(user_id: test_user_id, event_name: test_event_name)
end
end.not_to raise_error
end
end
end
describe 'private class methods' do
describe '.generate_cache_key' do
it 'generates correct cache key format' do
result = described_class.send(:generate_cache_key, user_id, event_name)
expect(result).to eq("#{user_id}:#{event_name}")
end
end
describe '.validate_inputs' do
it 'passes with valid inputs' do
expect do
described_class.send(:validate_inputs, user_id, event_name)
end.not_to raise_error
end
it 'raises error for blank user_id' do
expect do
described_class.send(:validate_inputs, '', event_name)
end.to raise_error(ArgumentError, 'user_id is required')
end
it 'raises error for blank event_name' do
expect do
described_class.send(:validate_inputs, user_id, '')
end.to raise_error(ArgumentError, 'event_name is required')
end
it 'raises error for event_name too long' do
long_name = 'a' * 51
expect do
described_class.send(:validate_inputs, user_id, long_name)
end.to raise_error(ArgumentError, 'event_name must be 50 characters or less')
end
end
describe 'cache methods' do
let(:test_key) { 'test_key' }
describe '.key_cached?' do
before do
allow(Rails.cache).to receive(:exist?)
end
it 'calls Rails.cache.exist? with correct parameters' do
described_class.send(:key_cached?, test_key)
expect(Rails.cache).to have_received(:exist?).with(test_key, namespace: 'unique_user_metrics')
end
end
describe '.mark_key_cached' do
before do
allow(Rails.cache).to receive(:write)
end
it 'calls Rails.cache.write with correct parameters' do
described_class.send(:mark_key_cached, test_key)
expect(Rails.cache).to have_received(:write).with(
test_key,
true,
namespace: 'unique_user_metrics',
expires_in: described_class::CACHE_TTL
)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/education_benefits_submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EducationBenefitsSubmission, type: :model do
subject { described_class.new(attributes) }
let(:attributes) do
{
region: 'eastern'
}
end
describe 'validations' do
it 'validates region is correct' do
subject.region = 'western'
expect_attr_valid(subject, :region)
subject.region = 'canada'
expect_attr_invalid(subject, :region, 'is not included in the list')
end
it 'validates form_type' do
%w[1995 1990 0993 0994 10203 10297].each do |form_type|
subject.form_type = form_type
expect_attr_valid(subject, form_type)
end
subject.form_type = 'foo'
expect_attr_invalid(subject, :form_type, 'is not included in the list')
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/saved_claim_group_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SavedClaimGroup, type: :model do
let(:parent) { create(:fake_saved_claim, id: 23) }
let(:child) { create(:fake_saved_claim, id: 42) }
let(:child2) { create(:fake_saved_claim, id: 43) }
let(:guid) { SecureRandom.uuid }
let(:guid2) { SecureRandom.uuid }
before do
allow_any_instance_of(SavedClaim).to receive :after_create_metrics
end
context 'a valid entry' do
it 'tracks a create event' do
tags = ["form_id:#{parent.form_id}", 'action:create']
expect(StatsD).to receive(:increment).with('saved_claim_group', tags:)
expect(Rails.logger).to receive(:info).with(/#{parent.form_id} 23 child #{child.form_id} 42/)
SavedClaimGroup.new(claim_group_guid: guid, parent_claim_id: parent.id, saved_claim_id: child.id).save
end
it 'returns expected claims' do
group = SavedClaimGroup.new(claim_group_guid: guid, parent_claim_id: parent.id, saved_claim_id: child.id)
group.save
expect(group.parent).to eq parent
expect(group.child).to eq child
expect(group.saved_claim_children.first).to eq child
end
it 'can be found from the parent claim' do
group = SavedClaimGroup.new(claim_group_guid: guid, parent_claim_id: parent.id, saved_claim_id: child.id)
group.save
expect(parent.parent_of_groups).to eq [group]
end
it 'returns child claims excluding parent' do
# Parent record (where parent_claim_id == saved_claim_id)
create(:saved_claim_group,
parent_claim_id: parent.id,
saved_claim_id: parent.id)
# Child record
child_group = create(:saved_claim_group,
parent_claim_id: parent.id,
saved_claim_id: child.id)
results = described_class.child_claims_for(parent.id)
expect(results).to eq([child_group])
end
end
describe 'scopes' do
let!(:parent_group) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: parent.id,
status: 'pending'
)
end
let!(:child_group1) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: child.id,
status: 'success'
)
end
let!(:child_group2) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: child2.id,
status: 'pending',
needs_kms_rotation: true
)
end
let!(:other_group) do
SavedClaimGroup.create!(
claim_group_guid: guid2,
parent_claim_id: child.id,
saved_claim_id: child.id,
status: 'pending'
)
end
describe '.by_claim_group_guid' do
it 'returns groups with matching claim_group_guid' do
results = SavedClaimGroup.by_claim_group_guid(guid)
expect(results).to contain_exactly(parent_group, child_group1, child_group2)
end
it 'returns empty collection when no matches' do
nonexistent_guid = SecureRandom.uuid
results = SavedClaimGroup.by_claim_group_guid(nonexistent_guid)
expect(results).to be_empty
end
end
describe '.by_saved_claim_id' do
it 'returns groups with matching saved_claim_id' do
results = SavedClaimGroup.by_saved_claim_id(child.id)
expect(results).to contain_exactly(child_group1, other_group)
end
it 'returns empty collection when no matches' do
results = SavedClaimGroup.by_saved_claim_id(999)
expect(results).to be_empty
end
end
describe '.by_parent_id' do
it 'returns groups with matching parent_claim_id' do
results = SavedClaimGroup.by_parent_id(parent.id)
expect(results).to contain_exactly(parent_group, child_group1, child_group2)
end
it 'returns empty collection when no matches' do
results = SavedClaimGroup.by_parent_id(999)
expect(results).to be_empty
end
end
describe '.by_status' do
it 'returns groups with matching status' do
results = SavedClaimGroup.by_status('pending')
expect(results).to contain_exactly(parent_group, child_group2, other_group)
end
it 'returns groups with success status' do
results = SavedClaimGroup.by_status('success')
expect(results).to contain_exactly(child_group1)
end
it 'returns empty collection when no matches' do
results = SavedClaimGroup.by_status('failure')
expect(results).to be_empty
end
end
describe '.pending' do
it 'returns only pending groups' do
results = SavedClaimGroup.pending
expect(results).to contain_exactly(parent_group, child_group2, other_group)
end
end
describe '.needs_kms_rotation' do
it 'returns only groups that need KMS rotation' do
results = SavedClaimGroup.needs_kms_rotation
expect(results).to contain_exactly(child_group2)
end
end
describe '.child_claims_for' do
it 'returns child groups excluding parent for given parent_id' do
results = SavedClaimGroup.child_claims_for(parent.id)
expect(results).to contain_exactly(child_group1, child_group2)
end
it 'excludes the parent record itself' do
results = SavedClaimGroup.child_claims_for(parent.id)
expect(results).not_to include(parent_group)
end
it 'returns empty collection when no children exist' do
results = SavedClaimGroup.child_claims_for(child.id)
expect(results).to be_empty
end
end
end
describe '#parent_claim_group_for_child' do
let!(:parent_group) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: parent.id
)
end
let!(:child_group) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: child.id
)
end
it 'returns the parent group record for a child group' do
result = child_group.parent_claim_group_for_child
expect(result).to eq(parent_group)
end
it 'returns self when called on parent group' do
result = parent_group.parent_claim_group_for_child
expect(result).to eq(parent_group)
end
it 'returns nil when parent group does not exist' do
orphan_group = SavedClaimGroup.create!(
claim_group_guid: guid2,
parent_claim_id: child2.id,
saved_claim_id: child.id
)
result = orphan_group.parent_claim_group_for_child
expect(result).to be_nil
end
end
describe '#children_of_group' do
let!(:parent_group) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: parent.id
)
end
let!(:child_group1) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: child.id
)
end
let!(:child_group2) do
SavedClaimGroup.create!(
claim_group_guid: guid,
parent_claim_id: parent.id,
saved_claim_id: child2.id
)
end
let!(:other_parent_group) do
SavedClaimGroup.create!(
claim_group_guid: guid2,
parent_claim_id: child.id,
saved_claim_id: child.id
)
end
it 'returns child groups for the same parent, excluding the parent itself' do
result = parent_group.children_of_group
expect(result).to contain_exactly(child_group1, child_group2)
end
it 'excludes the parent group record itself' do
result = parent_group.children_of_group
expect(result).not_to include(parent_group)
end
it 'returns empty collection when no children exist' do
result = other_parent_group.children_of_group
expect(result).to be_empty
end
it 'works correctly when called from a child group' do
result = child_group1.children_of_group
expect(result).to contain_exactly(child_group1, child_group2)
end
it 'does not include groups from different parents' do
result = parent_group.children_of_group
expect(result).not_to include(other_parent_group)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_credential_email_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserCredentialEmail, type: :model do
subject do
create(:user_credential_email,
user_verification:,
credential_email:)
end
let(:user_verification) { create(:user_verification) }
let(:credential_email) { 'some-credential-email' }
describe 'validations' do
context 'when user_verification is nil' do
let(:user_verification) { nil }
let(:expected_error_message) { 'Validation failed: User verification must exist' }
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_email is nil' do
let(:credential_email) { nil }
let(:expected_error_message) { "Validation failed: Credential email ciphertext 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
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form526_job_status_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Form526JobStatus do
describe '.upsert' do
let(:form526_submission) { create(:form526_submission) }
let(:jid) { SecureRandom.uuid }
let(:values) do
{
form526_submission_id: form526_submission.id,
job_id: jid,
job_class: 'SubmitForm526',
status: Form526JobStatus::STATUS[:success],
updated_at: Time.now.utc
}
end
it 'creates a record' do
expect do
Form526JobStatus.upsert(values, unique_by: :job_id)
end.to change(Form526JobStatus, :count).by(1)
end
end
describe '#success?' do
it 'returns true for new success statuses' do
success_statuses = %w[pdf_found_later pdf_success_on_backup_path pdf_manually_uploaded]
success_statuses.each do |status|
job_status = described_class.new(status:)
expect(job_status.success?).to be true
end
end
it 'returns false for failure statuses' do
failure_statuses = %w[non_retryable_error exhausted]
failure_statuses.each do |status|
job_status = described_class.new(status:)
expect(job_status.success?).to be false
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/tooltip_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Tooltip, type: :model do
context 'with valid attributes' do
subject { build(:tooltip) }
it { is_expected.to be_valid }
it { is_expected.to validate_presence_of(:tooltip_name) }
it { is_expected.to validate_presence_of(:last_signed_in) }
it { is_expected.to validate_uniqueness_of(:tooltip_name).scoped_to(:user_account_id) }
end
context 'with invalid attributes' do
it 'is invalid without a tooltip_name' do
tooltip = build(:tooltip, tooltip_name: nil)
expect(tooltip).not_to be_valid
expect(tooltip.errors[:tooltip_name]).to include('can\'t be blank')
end
it 'is invalid without a last_signed_in' do
tooltip = build(:tooltip, last_signed_in: nil)
expect(tooltip).not_to be_valid
expect(tooltip.errors[:last_signed_in]).to include('can\'t be blank')
end
it 'is invalid with a duplicate tooltip_name for the same user_account' do
user_account = create(:user_account)
create(:tooltip, user_account:, tooltip_name: 'duplicate_name')
tooltip = build(:tooltip, user_account:, tooltip_name: 'duplicate_name')
expect(tooltip).not_to be_valid
expect(tooltip.errors[:tooltip_name]).to include('has already been taken')
end
end
context 'associations' do
it 'belongs to a user_account' do
tooltip = build(:tooltip)
expect(tooltip).to respond_to(:user_account)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/in_progress_form_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe InProgressForm, type: :model do
let(:in_progress_form) { build(:in_progress_form) }
describe '#log_hca_email_diff' do
context 'with a 1010ez in progress form' do
it 'runs the hca email diff job' do
expect do
create(:in_progress_1010ez_form)
end.to change(HCA::LogEmailDiffJob.jobs, :size).by(1)
end
end
context 'with a non-1010ez in progress form' do
it 'doesnt run hca email diff job' do
create(:in_progress_form)
expect(HCA::LogEmailDiffJob.jobs.size).to eq(0)
end
end
end
describe 'form encryption' do
it 'encrypts the form data field' do
expect(subject).to encrypt_attr(:form_data)
end
end
describe 'validations' do
it 'validates presence of form_data' do
expect_attr_valid(in_progress_form, :form_data)
in_progress_form.form_data = nil
expect_attr_invalid(in_progress_form, :form_data, "can't be blank")
end
end
describe '#metadata' do
it 'adds the form creation time', run_at: '2023-09-15' do
in_progress_form.save
expect(in_progress_form.metadata['createdAt']).to eq(1_694_736_000)
end
end
describe '#serialize_form_data' do
let(:form_data) do
{ a: 1 }
end
it 'serializes form_data as json' do
in_progress_form.form_data = form_data
in_progress_form.save!
expect(in_progress_form.form_data).to eq(form_data.to_json)
end
end
describe 'scopes' do
let!(:first_record) do
create(:in_progress_form, metadata: { submission: { hasAttemptedSubmit: true,
errors: 'foo',
errorMessage: 'bar',
status: 'serverError' } })
end
let!(:second_record) do
create(:in_progress_form, metadata: { submission: { hasAttemptedSubmit: false, status: false } })
end
let!(:third_record) do
create(:in_progress_form, form_id: '5655', metadata: { submission: { hasAttemptedSubmit: true, status: false } })
end
let!(:fourth_record) do
create(:in_progress_form, form_id: '5655',
metadata: { submission: { hasAttemptedSubmit: true, status: 'applicationSubmitted' } })
end
it 'includes records within scope' do
expect(described_class.has_attempted_submit).to include(first_record)
expect(described_class.has_errors).to include(first_record)
expect(described_class.has_error_message).to include(first_record)
expect(described_class.has_no_errors).to include(second_record)
expect(described_class.unsubmitted_fsr).to include(third_record)
expect(described_class.unsubmitted_fsr.length).to eq(1)
end
end
describe '#expires_after' do
context 'when 21-526EZ' do
before do
in_progress_form.form_id = '21-526EZ'
end
it 'is an ActiveSupport::Duration' do
expect(in_progress_form.expires_after).to be_a(ActiveSupport::Duration)
end
it 'value is 1 year' do
expect(in_progress_form.expires_after).to eq(1.year)
end
end
context 'when unrecognized form' do
before do
in_progress_form.form_id = 'abcd-1234'
end
it 'is an ActiveSupport::Duration' do
expect(in_progress_form.expires_after).to be_a(ActiveSupport::Duration)
end
it 'value is 60 days' do
expect(in_progress_form.expires_after).to eq(60.days)
end
end
end
describe '.form_for_user' do
subject { InProgressForm.form_for_user(form_id, user) }
let(:form_id) { in_progress_form.form_id }
let(:user) { create(:user) }
context 'and in progress form exists associated with user uuid' do
let!(:in_progress_form_user_uuid) { create(:in_progress_form, user_uuid: user.uuid) }
it 'returns InProgressForms for user with given form id' do
expect(subject).to eq(in_progress_form_user_uuid)
end
end
context 'and in progress form does not exist associated with user uuid' do
context 'and in progress form exists associated with user account on user' do
let!(:in_progress_form_user_account) { create(:in_progress_form, user_account: user.user_account) }
it 'returns InProgressForms for user with given form id' do
expect(subject).to eq(in_progress_form_user_account)
end
end
end
context 'with with_lock parameter' do
subject { InProgressForm.form_for_user(form_id, user, with_lock: true) }
context 'when in_progress_form_atomicity flipper is enabled' do
before do
allow(Flipper).to receive(:enabled?).with(:in_progress_form_atomicity, user).and_return(true)
end
context 'and in progress form exists' do
let!(:in_progress_form_user_uuid) { create(:in_progress_form, user_uuid: user.uuid) }
it 'returns the form with a lock' do
expect(InProgressForm).to receive(:lock).and_call_original
expect(subject).to eq(in_progress_form_user_uuid)
end
end
context 'and in progress form does not exist' do
it 'returns nil' do
expect(InProgressForm).to receive(:lock).and_call_original
expect(subject).to be_nil
end
end
end
context 'when in_progress_form_atomicity flipper is disabled' do
before do
allow(Flipper).to receive(:enabled?).with(:in_progress_form_atomicity, user).and_return(false)
end
context 'and in progress form exists' do
let!(:in_progress_form_user_uuid) { create(:in_progress_form, user_uuid: user.uuid) }
it 'returns the form without a lock' do
expect(InProgressForm).not_to receive(:lock)
expect(subject).to eq(in_progress_form_user_uuid)
end
end
end
end
end
describe '.for_user' do
subject { InProgressForm.for_user(user) }
let(:user) { create(:user) }
let!(:in_progress_form_user_uuid) { create(:in_progress_form, user_uuid: user.uuid) }
let!(:in_progress_form_user_account) { create(:in_progress_form, user_account: user.user_account) }
let(:expected_in_progress_forms_id) { [in_progress_form_user_uuid.id, in_progress_form_user_account.id] }
it 'returns in progress forms associated with user uuid and user account' do
expect(subject.map(&:id)).to match_array(expected_in_progress_forms_id)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/redis_caching_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe RedisCaching do
describe '#get_cached' do
it 'returns nil when nil value was set' do
Message.set_cached('test-nil-cache-key', nil)
expect(Message.get_cached('test-nil-cache-key')).to be_nil
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/evss_claim_document_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EVSSClaimDocument do
describe 'validations' do
describe '#convert_to_unlock_pdf' do
let(:tracked_item_id) { 33 }
let(:document_type) { 'L023' }
let(:file_name) { 'locked_pdf_password_is_test.pdf' }
let(:bad_password) { 'bad_pw' }
context 'when provided password is incorrect' do
it 'logs a sanitized message to Sentry' do
error_message = nil
allow_any_instance_of(EVSSClaimDocument).to receive(:log_message_to_sentry) do |_, message, _level|
error_message = message
end
tempfile = Tempfile.new(['', "-#{file_name}"])
file_obj = ActionDispatch::Http::UploadedFile.new(original_filename: file_name, type: 'application/pdf',
tempfile:)
document = EVSSClaimDocument.new(
file_obj:,
file_name:,
tracked_item_id:,
document_type:,
password: bad_password
)
expect(document).not_to be_valid
expect(error_message).not_to include(file_name)
expect(error_message).not_to include(bad_password)
end
end
end
end
describe '#to_serializable_hash' do
it 'does not return file_obj' do
f = Tempfile.new(['file with spaces', '.txt'])
f.write('test')
f.rewind
rack_file = Rack::Test::UploadedFile.new(f.path, 'text/plain')
upload_file = ActionDispatch::Http::UploadedFile.new(
tempfile: rack_file.tempfile,
filename: rack_file.original_filename,
type: rack_file.content_type
)
document = EVSSClaimDocument.new(
evss_claim_id: 1,
tracked_item_id: 1,
file_obj: upload_file,
file_name: File.basename(upload_file.path)
)
expect(document.to_serializable_hash.keys).not_to include(:file_obj)
expect(document.to_serializable_hash.keys).not_to include('file_obj')
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form526_submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'disability_compensation/factories/api_provider_factory'
RSpec.describe Form526Submission do
subject do
Form526Submission.create(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: auth_headers.to_json,
form_json:,
submit_endpoint:,
backup_submitted_claim_status:
)
end
let(:user_account) { user.user_account }
let(:user) do
create(:user, :loa3, first_name: 'Beyonce', last_name: 'Knowles', icn:)
end
let(:icn) { 'some-icn' }
let(:auth_headers) do
EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h)
end
let(:saved_claim) { create(:va526ez) }
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526.json')
end
let(:submit_endpoint) { nil }
let(:backup_submitted_claim_status) { nil }
before do
allow(Flipper).to receive(:enabled?).and_call_original
end
describe 'associations' do
it { is_expected.to have_many(:form526_submission_remediations) }
end
describe 'submit_endpoint enum' do
context 'when submit_endpoint is evss' do
let(:submit_endpoint) { 'evss' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when submit_endpoint is claims_api' do
let(:submit_endpoint) { 'claims_api' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when submit_endpoint is benefits_intake_api' do
let(:submit_endpoint) { 'benefits_intake_api' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when submit_endpoint is not evss, claims_api or benefits_intake_api' do
it 'is invalid' do
expect do
subject.submit_endpoint = 'other_value'
end.to raise_error(ArgumentError, "'other_value' is not a valid submit_endpoint")
end
end
end
describe 'backup_submitted_claim_status enum' do
context 'when backup_submitted_claim_status is nil' do
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when backup_submitted_claim_status is accepted' do
let(:backup_submitted_claim_status) { 'accepted' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when backup_submitted_claim_status is rejected' do
let(:backup_submitted_claim_status) { 'rejected' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when backup_submitted_claim_status is paranoid_success' do
let(:backup_submitted_claim_status) { 'paranoid_success' }
it 'is valid' do
expect(subject).to be_valid
end
end
context 'when backup_submitted_claim_status is neither accepted, rejected nor nil' do
it 'is invalid' do
expect do
subject.backup_submitted_claim_status = 'other_value'
end.to raise_error(ArgumentError, "'other_value' is not a valid backup_submitted_claim_status")
end
end
end
describe 'scopes' do
let!(:in_process) { create(:form526_submission) }
let!(:expired) { create(:form526_submission, :created_more_than_3_weeks_ago) }
let!(:happy_path_success) { create(:form526_submission, :with_submitted_claim_id) }
let!(:happy_lighthouse_path_success) do
create(:form526_submission, :with_submitted_claim_id, submit_endpoint: 'claims_api')
end
let!(:pending_backup) { create(:form526_submission, :backup_path) }
let!(:accepted_backup) { create(:form526_submission, :backup_path, :backup_accepted) }
let!(:rejected_backup) { create(:form526_submission, :backup_path, :backup_rejected) }
let!(:remediated) { create(:form526_submission, :remediated) }
let!(:remediated_and_expired) { create(:form526_submission, :remediated, :created_more_than_3_weeks_ago) }
let!(:remediated_and_rejected) { create(:form526_submission, :remediated, :backup_path, :backup_rejected) }
let!(:new_no_longer_remediated) { create(:form526_submission, :no_longer_remediated) }
let!(:old_no_longer_remediated) do
Timecop.freeze(3.months.ago) do
create(:form526_submission, :no_longer_remediated)
end
end
let!(:paranoid_success) { create(:form526_submission, :backup_path, :paranoid_success) }
let!(:success_by_age) do
Timecop.freeze((1.year + 1.day).ago) do
create(:form526_submission, :backup_path, :paranoid_success)
end
end
let!(:failed_primary) { create(:form526_submission, :with_failed_primary_job) }
let!(:exhausted_primary) { create(:form526_submission, :with_exhausted_primary_job) }
let!(:failed_backup) { create(:form526_submission, :with_failed_backup_job) }
let!(:exhausted_backup) { create(:form526_submission, :with_exhausted_backup_job) }
before do
happy_lighthouse_path_success.form526_job_statuses << Form526JobStatus.new(
job_class: 'PollForm526Pdf',
status: Form526JobStatus::STATUS[:success],
job_id: 1
)
end
describe 'with_exhausted_primary_jobs' do
it 'returns submissions associated to failed or exhausted primary jobs' do
expect(Form526Submission.with_exhausted_primary_jobs).to contain_exactly(
failed_primary,
exhausted_primary
)
end
end
describe 'with_exhausted_backup_jobs' do
it 'returns submissions associated to failed or exhausted backup jobs' do
expect(Form526Submission.with_exhausted_backup_jobs).to contain_exactly(
failed_backup,
exhausted_backup
)
end
end
describe 'paranoid_success_type' do
it 'returns records less than a year old with paranoid_success backup status' do
expect(Form526Submission.paranoid_success_type).to contain_exactly(
paranoid_success
)
end
end
describe 'success_by_age' do
it 'returns records more than a year old with paranoid_success backup status' do
expect(Form526Submission.success_by_age).to contain_exactly(
success_by_age
)
end
end
describe 'pending_backup' do
it 'returns records submitted to the backup path but lacking a decisive state' do
expect(Form526Submission.pending_backup).to contain_exactly(
pending_backup
)
end
end
describe 'in_process' do
it 'only returns submissions that are still in process' do
expect(Form526Submission.in_process).to contain_exactly(
in_process,
new_no_longer_remediated,
exhausted_primary,
failed_primary
)
end
end
describe 'incomplete_type' do
it 'only returns submissions that are still in process' do
expect(Form526Submission.incomplete_type).to contain_exactly(
in_process,
pending_backup,
new_no_longer_remediated,
exhausted_primary,
failed_primary
)
end
end
describe 'accepted_to_primary_path' do
it 'returns submissions with a submitted_claim_id' do
expect(Form526Submission.accepted_to_evss_primary_path).to contain_exactly(
happy_path_success
)
end
it 'returns Lighthouse submissions with a found PDF with a submitted_claim_id' do
expect(Form526Submission.accepted_to_lighthouse_primary_path).to contain_exactly(
happy_lighthouse_path_success
)
end
it 'returns both an EVSS submission and a Lighthouse submission with a found PDF and a submitted_claim_id' do
expect(Form526Submission.accepted_to_primary_path).to contain_exactly(
happy_path_success, happy_lighthouse_path_success
)
end
it 'does not return the LH submission when the PDF is not found' do
happy_lighthouse_path_success.form526_job_statuses.last.update(
status: Form526JobStatus::STATUS[:pdf_not_found]
)
expect(Form526Submission.accepted_to_lighthouse_primary_path).to be_empty
end
it 'returns the EVSS submission when the Lighthouse submission is not found' do
happy_lighthouse_path_success.update(submitted_claim_id: nil)
expect(Form526Submission.accepted_to_primary_path).to contain_exactly(
happy_path_success
)
end
it 'returns the Lighthouse submission when the EVSS submission has no submitted claim id' do
happy_path_success.update(submitted_claim_id: nil)
expect(Form526Submission.accepted_to_primary_path).to contain_exactly(
happy_lighthouse_path_success
)
end
it 'returns neither submission when neither EVSS nor Lighthouse submissions have submitted claim ids' do
happy_path_success.update(submitted_claim_id: nil)
happy_lighthouse_path_success.update(submitted_claim_id: nil)
expect(Form526Submission.accepted_to_primary_path).to be_empty
end
end
describe 'accepted_to_backup_path' do
it 'returns submissions with a backup_submitted_claim_id that have been explicitly accepted' do
expect(Form526Submission.accepted_to_backup_path).to contain_exactly(
accepted_backup,
paranoid_success,
success_by_age
)
end
end
describe 'rejected_from_backup_path' do
it 'returns submissions with a backup_submitted_claim_id that have been explicitly rejected' do
expect(Form526Submission.rejected_from_backup_path).to contain_exactly(
rejected_backup,
remediated_and_rejected
)
end
end
describe 'remediated' do
it 'returns everything with a successful remediation' do
expect(Form526Submission.remediated).to contain_exactly(
remediated,
remediated_and_expired,
remediated_and_rejected
)
end
end
describe 'success_type' do
it 'returns all submissions on which no further action is required' do
expect(Form526Submission.success_type).to contain_exactly(
remediated,
remediated_and_expired,
remediated_and_rejected,
happy_path_success,
happy_lighthouse_path_success,
accepted_backup,
paranoid_success,
success_by_age
)
end
end
describe 'failure_type' do
it 'returns anything not explicitly successful or still in process' do
expect(Form526Submission.failure_type).to contain_exactly(
rejected_backup,
expired,
old_no_longer_remediated,
failed_backup,
exhausted_backup
)
end
it 'handles the edge case where a submission succeeds during query building' do
expired.update!(submitted_claim_id: 'abc123')
expect(Form526Submission.failure_type).to contain_exactly(
rejected_backup,
old_no_longer_remediated,
failed_backup,
exhausted_backup
)
end
end
end
shared_examples '#start_evss_submission' do
context 'when it is all claims' do
it 'queues an all claims job' do
expect do
subject.start_evss_submission_job
end.to change(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim.jobs, :size).by(1)
end
end
end
describe '#start' do
context 'the submission is for hypertension' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526_hypertension.json')
end
it_behaves_like '#start_evss_submission'
end
context 'the submission is NOT for hypertension' do
it_behaves_like '#start_evss_submission'
end
context 'CFI metric logging' do
let!(:in_progress_form) do
ipf = create(:in_progress_526_form, user_uuid: user.uuid)
fd = ipf.form_data
fd = JSON.parse(fd)
fd['rated_disabilities'] = rated_disabilities
ipf.update!(form_data: fd)
ipf
end
before do
allow(StatsD).to receive(:increment)
allow(Rails.logger).to receive(:info)
end
def expect_submit_log(num_max_rated, num_max_rated_cfi, total_cfi)
expect(Rails.logger).to have_received(:info).with(
'Max CFI form526 submission',
{ id: subject.id,
num_max_rated:,
num_max_rated_cfi:,
total_cfi:,
cfi_checkbox_was_selected: false }
)
end
def expect_max_cfi_logged(disability_claimed, diagnostic_code)
expect(StatsD).to have_received(:increment).with('api.max_cfi.submit',
tags: ["diagnostic_code:#{diagnostic_code}",
"claimed:#{disability_claimed}"])
end
def expect_no_max_cfi_logged(diagnostic_code)
expect(StatsD).not_to have_received(:increment).with('api.max_cfi.submit',
tags: ["diagnostic_code:#{diagnostic_code}",
anything])
end
context 'the submission is for tinnitus' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526_tinnitus.json')
end
let(:rated_disabilities) do
[
{ name: 'Tinnitus',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::TINNITUS,
rating_percentage:,
maximum_rating_percentage: 10 }
]
end
let(:rating_percentage) { 0 }
context 'Rated Tinnitus is at maximum' do
let(:rating_percentage) { 10 }
it 'logs CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 6260)
expect_submit_log(1, 1, 1)
end
end
context 'Rated Tinnitus is not at maximum' do
it 'logs CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:false', 'has_max_rated:false'])
expect_no_max_cfi_logged(6260)
end
end
end
context 'the submission is for hypertension with no max rating percentage' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526_hypertension.json')
end
let(:rated_disabilities) do
[
{ name: 'Hypertension',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::HYPERTENSION,
rating_percentage: 20 }
]
end
it 'logs CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:false', 'has_max_rated:false'])
expect_no_max_cfi_logged(7101)
expect_submit_log(0, 0, 1)
end
end
context 'the submission for single cfi for a Veteran with multiple rated conditions' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526_hypertension.json')
end
let(:rated_disabilities) do
[
{ name: 'Tinnitus',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::TINNITUS,
rating_percentage: rating_percentage_tinnitus,
maximum_rating_percentage: 10 },
{ name: 'Hypertension',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::HYPERTENSION,
rating_percentage: rating_percentage_hypertension,
maximum_rating_percentage: 60 }
]
end
let(:rating_percentage_tinnitus) { 0 }
let(:rating_percentage_hypertension) { 0 }
context 'Rated Disabilities are not at maximum' do
it 'logs CFI metric upon submission for only hypertension' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:false', 'has_max_rated:false'])
expect_no_max_cfi_logged(6260)
expect_no_max_cfi_logged(7101)
expect_submit_log(0, 0, 1)
end
end
context 'Rated Disabilities of cfi is at maximum' do
let(:rating_percentage_hypertension) { 60 }
it 'logs CFI metric upon submission for only hypertension' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 7101)
expect_submit_log(1, 1, 1)
expect_no_max_cfi_logged(6260)
end
end
context 'All Rated Disabilities at maximum' do
let(:rating_percentage_tinnitus) { 10 }
let(:rating_percentage_hypertension) { 60 }
it 'logs CFI metric upon submission for only hypertension' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 7101)
expect_max_cfi_logged(false, 6260)
expect_submit_log(2, 1, 1)
end
end
end
context 'the submission for multiple cfi for a Veteran with multiple rated conditions' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/only_526_two_cfi_with_max_ratings.json')
end
let(:rated_disabilities) do
[
{ name: 'Tinnitus',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::TINNITUS,
rating_percentage: rating_percentage_tinnitus,
maximum_rating_percentage: 10 },
{ name: 'Hypertension',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::HYPERTENSION,
rating_percentage: rating_percentage_hypertension,
maximum_rating_percentage: 60 }
]
end
let(:rating_percentage_tinnitus) { 0 }
let(:rating_percentage_hypertension) { 0 }
context 'Rated Disabilities are not at maximum' do
it 'does not log CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:false', 'has_max_rated:false'])
expect_no_max_cfi_logged(6260)
expect_no_max_cfi_logged(7101)
expect_submit_log(0, 0, 2)
end
end
context 'Rated Disabilities are at maximum' do
let(:rating_percentage_tinnitus) { 10 }
let(:rating_percentage_hypertension) { 60 }
it 'logs CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 6260)
expect_max_cfi_logged(true, 7101)
expect_submit_log(2, 2, 2)
end
end
context 'Only Tinnitus is rated at the maximum' do
let(:rating_percentage_tinnitus) { 10 }
it 'logs CFI metric upon submission only for tinnitus' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 6260)
expect_no_max_cfi_logged(7101)
expect_submit_log(1, 1, 2)
end
end
context 'Only Hypertension is rated at the maximum' do
let(:rating_percentage_hypertension) { 60 }
it 'does not log CFI metric upon submission' do
subject.start
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_submit',
tags: ['claimed:true', 'has_max_rated:true'])
expect_max_cfi_logged(true, 7101)
expect_no_max_cfi_logged(6260)
expect_submit_log(1, 1, 2)
end
end
end
end
end
describe '#start_evss_submission_job' do
it_behaves_like '#start_evss_submission'
end
describe '#submit_with_birls_id_that_hasnt_been_tried_yet!' do
context 'when it is all claims' do
it 'queues an all claims job' do
expect(subject.birls_id).to be_truthy
expect(subject.birls_ids.count).to eq 1
subject.birls_ids_tried = { subject.birls_id => ['some timestamp'] }.to_json
subject.save!
expect { subject.submit_with_birls_id_that_hasnt_been_tried_yet! }.not_to(
change(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim.jobs, :size)
)
next_birls_id = "#{subject.birls_id}cat"
subject.add_birls_ids next_birls_id
expect { subject.submit_with_birls_id_that_hasnt_been_tried_yet! }.to(
change(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim.jobs, :size).by(1)
)
expect(subject.birls_id).to eq next_birls_id
end
end
end
describe '#form' do
it 'returns the form as a hash' do
expect(subject.form).to eq(JSON.parse(form_json))
end
end
describe '#form_to_json' do
context 'with form 526' do
it 'returns the sub form as json' do
expect(subject.form_to_json(Form526Submission::FORM_526)).to eq(JSON.parse(form_json)['form526'].to_json)
end
end
context 'with form 4142' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_4142.json')
end
it 'returns the sub form as json' do
expect(subject.form_to_json(Form526Submission::FORM_4142)).to eq(JSON.parse(form_json)['form4142'].to_json)
end
end
context 'with form 0781' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_0781.json')
end
it 'returns the sub form as json' do
expect(subject.form_to_json(Form526Submission::FORM_0781)).to eq(JSON.parse(form_json)['form0781'].to_json)
end
end
context 'with form 8940' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_8940.json')
end
it 'returns the sub form as json' do
expect(subject.form_to_json(Form526Submission::FORM_8940)).to eq(JSON.parse(form_json)['form8940'].to_json)
end
end
end
describe '#auth_headers' do
it 'returns the parsed auth headers' do
expect(subject.auth_headers).to eq(auth_headers)
end
end
describe '#add_birls_ids' do
subject do
headers = JSON.parse auth_headers.to_json
Form526Submission.new(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: headers.to_json,
form_json:,
birls_ids_tried: birls_ids_tried.to_json
)
end
context 'birls_ids_tried nil' do
let(:birls_ids_tried) { nil }
it 'has no default' do
expect(subject.birls_ids_tried).to eq 'null'
end
context 'using nil as an id' do
it 'results in an empty hash' do
subject.add_birls_ids nil
expect(JSON.parse(subject.birls_ids_tried)).to be_a Hash
end
end
context 'single id' do
it 'initializes with an empty array' do
subject.add_birls_ids 'a'
expect(subject.birls_ids_tried_hash).to eq 'a' => []
end
end
context 'an array of ids' do
it 'initializes with an empty arrays' do
subject.add_birls_ids(%w[a b c])
expect(subject.birls_ids_tried_hash).to eq 'a' => [], 'b' => [], 'c' => []
end
end
end
context 'birls_ids_tried already has values' do
let(:birls_ids_tried) { { 'a' => ['2021-02-01T14:28:33Z'] } }
context 'using nil as an id' do
it 'results in an empty hash' do
subject.add_birls_ids nil
expect(subject.birls_ids_tried_hash).to eq birls_ids_tried
end
end
context 'single id that is already present' do
it 'does nothing' do
subject.add_birls_ids 'a'
expect(subject.birls_ids_tried_hash).to eq birls_ids_tried
end
end
context 'single id that is not already present' do
it 'does nothing' do
subject.add_birls_ids 'b'
expect(subject.birls_ids_tried_hash).to eq birls_ids_tried.merge('b' => [])
end
end
context 'an array of ids' do
it 'initializes with an empty arrays, for ids that area not already present' do
subject.add_birls_ids(['a', :b, :c])
expect(subject.birls_ids_tried_hash).to eq birls_ids_tried.merge('b' => [], 'c' => [])
end
end
context 'an array of ids persisted' do
it 'persists' do
subject.add_birls_ids(['a', :b, :c])
subject.save
subject.reload
expect(subject.birls_ids_tried_hash).to eq birls_ids_tried.merge('b' => [], 'c' => [])
end
end
end
end
describe '#birls_ids' do
subject do
headers = JSON.parse auth_headers.to_json
headers['va_eauth_birlsfilenumber'] = birls_id
Form526Submission.new(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: headers.to_json,
form_json:,
birls_ids_tried: birls_ids_tried.to_json
)
end
let(:birls_id) { 'a' }
let(:birls_ids_tried) { { b: [], c: ['2021-02-01T14:28:33Z'] } }
context 'birls_ids_tried present and auth_headers present' do
it 'lists all birls ids' do
expect(subject.birls_ids).to contain_exactly 'c', 'b', 'a'
end
it 'persists' do
subject.save
subject.reload
expect(subject.birls_ids).to contain_exactly 'b', 'c', 'a'
end
end
context 'only birls_ids_tried present' do
subject do
Form526Submission.new(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
form_json:,
birls_ids_tried: birls_ids_tried.to_json
)
end
it 'lists birls ids from birls_ids_tried only' do
expect(subject.birls_ids).to contain_exactly 'b', 'c'
end
end
context 'only auth_headers present' do
let(:birls_ids_tried) { nil }
it 'lists birls ids from auth_headers only' do
expect(subject.birls_ids).to contain_exactly 'a'
end
end
end
describe '#mark_birls_id_as_tried' do
subject do
headers = JSON.parse auth_headers.to_json
headers['va_eauth_birlsfilenumber'] = birls_id
Form526Submission.new(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: headers.to_json,
form_json:,
birls_ids_tried: birls_ids_tried.to_json
)
end
let(:birls_id) { 'a' }
context 'nil birls_ids_tried' do
let(:birls_ids_tried) { nil }
it 'adds the current birls id to birls_ids_tried' do
expect(JSON.parse(subject.birls_ids_tried)).to eq birls_ids_tried
subject.mark_birls_id_as_tried
expect(subject.birls_ids_tried_hash.keys).to contain_exactly 'a'
subject.save
subject.reload
expect(subject.birls_ids_tried_hash.keys).to contain_exactly 'a'
end
end
context 'previous attempts' do
let(:birls_ids_tried) { { 'b' => ['2021-02-01T14:28:33Z'] } }
it 'adds the current BIRLS ID to birls_ids_tried array (turns birls_ids_tried into an array if nil)' do
expect(JSON.parse(subject.birls_ids_tried)).to eq birls_ids_tried
subject.mark_birls_id_as_tried
expect(subject.birls_ids_tried_hash.keys).to contain_exactly(birls_id, *birls_ids_tried.keys)
subject.save
subject.reload
expect(subject.birls_ids_tried_hash.keys).to contain_exactly(birls_id, *birls_ids_tried.keys)
end
end
end
describe '#birls_ids_that_havent_been_tried_yet' do
subject do
headers = JSON.parse auth_headers.to_json
headers['va_eauth_birlsfilenumber'] = birls_id
Form526Submission.new(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: headers.to_json,
form_json:,
birls_ids_tried: birls_ids_tried.to_json
)
end
let(:birls_id) { 'a' }
let(:birls_ids_tried) { { b: [], c: ['2021-02-01T14:28:33Z'], d: nil } }
it 'does not include birls ids that have already been tried' do
expect(subject.birls_ids_that_havent_been_tried_yet).to contain_exactly('a', 'b', 'd')
end
end
describe '#birls_id!' do
it 'returns the BIRLS ID' do
expect(subject.birls_id!).to eq(auth_headers[described_class::BIRLS_KEY])
end
context 'auth_headers is nil' do
it 'throws an exception' do
subject.auth_headers_json = nil
expect { subject.birls_id! }.to raise_error TypeError
end
end
context 'auth_headers is unparseable' do
it 'throws an exception' do
subject.auth_headers_json = 'hi!'
expect { subject.birls_id! }.to raise_error JSON::ParserError
end
end
end
describe '#birls_id' do
it 'returns the BIRLS ID' do
expect(subject.birls_id).to eq(auth_headers[described_class::BIRLS_KEY])
end
context 'auth_headers is nil' do
it 'returns nil' do
subject.auth_headers_json = nil
expect(subject.birls_id).to be_nil
end
end
context 'auth_headers is unparseable' do
it 'throws an exception' do
subject.auth_headers_json = 'hi!'
expect { subject.birls_id }.to raise_error JSON::ParserError
end
end
end
describe '#birls_id=' do
let(:birls_id) { 1 }
it 'sets the BIRLS ID' do
subject.birls_id = birls_id
expect(subject.birls_id).to eq(birls_id)
end
context 'auth_headers is nil' do
it 'throws an exception' do
subject.auth_headers_json = nil
expect { subject.birls_id = birls_id }.to raise_error TypeError
end
end
context 'auth_headers is unparseable' do
it 'throws an exception' do
subject.auth_headers_json = 'hi!'
expect { subject.birls_id = birls_id }.to raise_error JSON::ParserError
end
end
end
describe '#perform_ancillary_jobs_handler' do
let(:status) { OpenStruct.new(parent_bid: SecureRandom.hex(8)) }
context 'with 1 duplicate uploads' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_duplicate_uploads.json')
end
it 'queues 3 jobs with 1 duplicate at the right delay' do
# 3 files with 1 duplicate
# Should queue 3 jobs
# Job1 at 60 seconds
# Job2 at 360 seconds
# Job3 at 180 seconds
Timecop.freeze(Time.zone.now) do
subject.form526_job_statuses <<
Form526JobStatus.new(job_class: 'SubmitForm526AllClaim', status: 'success', job_id: 0)
expect do
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end.to change(EVSS::DisabilityCompensationForm::SubmitUploads.jobs, :size).by(3)
expect(EVSS::DisabilityCompensationForm::SubmitUploads.jobs.map do |h|
(h['at'] - Time.now.to_i).floor(0)
end).to eq([60, 360, 180])
end
end
end
context 'with many duplicate uploads' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_many_duplicate_uploads.json')
end
it 'queues jobs with many duplicates at the right delay' do
Timecop.freeze(Time.zone.now) do
subject.form526_job_statuses <<
Form526JobStatus.new(job_class: 'SubmitForm526AllClaim', status: 'success', job_id: 0)
expect do
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end.to change(EVSS::DisabilityCompensationForm::SubmitUploads.jobs, :size).by(7)
expect(EVSS::DisabilityCompensationForm::SubmitUploads.jobs.map do |h|
(h['at'] - Time.now.to_i).floor(0)
end).to eq([
60, # original file, 60s
360, # dup, plus 300s
660, # dup, plus 300s
960, # dup, plus 300s
1260, # dup, plus 300s
1560, # dup, plus 300s
420 # not a dup, (index+1 * 60)s
])
end
end
end
context 'with an ancillary job' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_uploads.json')
end
it 'queues 3 jobs' do
subject.form526_job_statuses <<
Form526JobStatus.new(job_class: 'SubmitForm526AllClaim', status: 'success', job_id: 0)
expect do
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end.to change(EVSS::DisabilityCompensationForm::SubmitUploads.jobs, :size).by(3)
end
it 'queues 3 jobs with no duplicates at the right delay' do
Timecop.freeze(Time.zone.now) do
subject.form526_job_statuses <<
Form526JobStatus.new(job_class: 'SubmitForm526AllClaim', status: 'success', job_id: 0)
expect do
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end.to change(EVSS::DisabilityCompensationForm::SubmitUploads.jobs, :size).by(3)
expect(EVSS::DisabilityCompensationForm::SubmitUploads.jobs.map do |h|
(h['at'] - Time.now.to_i).floor(0)
end).to eq([60, 120, 180])
end
end
it 'warns when there are multiple successful submit526 jobs' do
2.times do |index|
subject.form526_job_statuses << Form526JobStatus.new(
job_class: 'SubmitForm526AllClaim',
status: Form526JobStatus::STATUS[:success],
job_id: index
)
end
expect(Form526JobStatus.all.count).to eq 2
expect(Rails.logger).to receive(:warn).with(
'There are multiple successful SubmitForm526 job statuses',
{ form_526_submission_id: subject.id }
)
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end
it "warns when there's a successful submit526 job, but it's not the most recent submit526 job" do
%i[success retryable_error].each_with_index do |status, index|
subject.form526_job_statuses << Form526JobStatus.new(
job_class: 'SubmitForm526AllClaim',
status: Form526JobStatus::STATUS[status],
job_id: index,
updated_at: Time.zone.now + index.days
)
end
expect(Form526JobStatus.all.count).to eq 2
expect(Rails.logger).to receive(:warn).with(
"There is a successful SubmitForm526 job, but it's not the most recent SubmitForm526 job",
{ form_526_submission_id: subject.id }
)
subject.perform_ancillary_jobs_handler(status, 'submission_id' => subject.id)
end
end
end
describe '#perform_ancillary_jobs' do
let(:first_name) { 'firstname' }
context 'with (3) uploads' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_uploads.json')
end
it 'queues 3 upload jobs' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(EVSS::DisabilityCompensationForm::SubmitUploads.jobs, :size).by(3)
end
end
context 'with flashes' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_uploads.json')
end
context 'when feature enabled' do
before { Flipper.enable(:disability_compensation_flashes) }
it 'queues flashes job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(BGS::FlashUpdater.jobs, :size).by(1)
end
end
context 'when feature disabled' do
before { Flipper.disable(:disability_compensation_flashes) }
it 'queues flashes job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.not_to change(BGS::FlashUpdater.jobs, :size)
end
end
end
context 'BDD' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/526_bdd.json')
end
it 'queues 1 UploadBddInstructions job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(EVSS::DisabilityCompensationForm::UploadBddInstructions.jobs, :size).by(1)
end
end
context 'with form 4142' do
before do
allow(Flipper).to receive(:enabled?).with(:validate_saved_claims_with_json_schemer).and_return(false)
allow(Flipper).to receive(:enabled?).with(:disability_compensation_production_tester).and_return(false)
allow(Flipper).to receive(:enabled?).with(:disability_compensation_production_tester,
anything).and_return(false)
end
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_4142.json')
end
it 'queues a 4142 job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(CentralMail::SubmitForm4142Job.jobs, :size).by(1)
end
end
context 'with form 0781' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_0781.json')
end
it 'queues a 0781 job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(EVSS::DisabilityCompensationForm::SubmitForm0781.jobs, :size).by(1)
end
end
context 'with form 8940' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_8940.json')
end
it 'queues a 8940 job' do
expect do
subject.perform_ancillary_jobs(first_name)
end.to change(EVSS::DisabilityCompensationForm::SubmitForm8940.jobs, :size).by(1)
end
end
context 'with Lighthouse document upload polling' do
let(:form_json) do
File.read('spec/support/disability_compensation_form/submissions/with_uploads.json')
end
it 'queues polling job' do
expect do
form = subject.saved_claim.parsed_form
form['startedFormVersion'] = '2022'
subject.update(submitted_claim_id: 1)
subject.saved_claim.update(form: form.to_json)
subject.perform_ancillary_jobs(first_name)
end.to change(Lighthouse::PollForm526Pdf.jobs, :size).by(1)
end
end
end
describe '#get_first_name' do
[
{
input: 'Joe',
expected: 'JOE'
},
{
input: 'JOE',
expected: 'JOE'
}, {
input: 'joe mark',
expected: 'JOE MARK'
}
].each do |test_param|
it 'gets correct first name' do
allow(User).to receive(:find).with(anything).and_return(user)
allow_any_instance_of(User).to receive(:first_name).and_return(test_param[:input])
expect(subject.get_first_name).to eql(test_param[:expected])
end
end
context 'when the first name is NOT populated on the User' do
before do
# Ensure `subject` is called before stubbing `first_name` so that the auth headers are populated correctly
subject
user_with_nil_first_name = User.create(user)
allow(user_with_nil_first_name).to receive(:first_name).and_return nil
allow(User).to receive(:find).with(subject.user_uuid).and_return user_with_nil_first_name
end
context 'when name attributes exist in the auth headers' do
it 'returns the first name of the user from the auth headers' do
expect(subject.get_first_name).to eql('BEYONCE')
end
end
context 'when name attributes do NOT exist in the auth headers' do
subject { build(:form526_submission, :with_empty_auth_headers) }
it 'returns nil' do
expect(subject.get_first_name).to be_nil
end
end
end
context 'when the User is NOT found' do
before { allow(User).to receive(:find).and_return nil }
it 'returns the first name of the user from the auth headers' do
expect(subject.get_first_name).to eql('BEYONCE')
end
end
end
describe '#full_name' do
let(:full_name_hash) do
{
first: 'Beyonce',
middle: nil,
last: 'Knowles',
suffix: user.normalized_suffix
}
end
context 'when the full name exists on the User' do
it 'returns the full name of the user' do
expect(subject.full_name).to eql(full_name_hash)
end
end
context 'when the full name is NOT populated on the User but name attributes exist in the auth_headers' do
let(:nil_full_name_hash) do
{
first: nil,
middle: nil,
last: nil,
suffix: nil
}
end
before do
allow_any_instance_of(User).to receive(:full_name_normalized).and_return nil_full_name_hash
end
context 'when name attributes exist in the auth headers' do
it 'returns the first and last name of the user from the auth headers' do
expect(subject.full_name).to eql(full_name_hash.merge(middle: nil, suffix: nil))
end
end
context 'when name attributes do NOT exist in the auth headers' do
subject { build(:form526_submission, :with_empty_auth_headers) }
it 'returns the hash with all nil values' do
expect(subject.full_name).to eql nil_full_name_hash
end
end
end
context 'when the User is NOT found' do
before { allow(User).to receive(:find).and_return nil }
it 'returns the first and last name of the user from the auth headers' do
expect(subject.full_name).to eql(full_name_hash.merge(middle: nil, suffix: nil))
end
end
end
describe '#workflow_complete_handler' do
describe 'success' do
let(:options) do
{
'submission_id' => subject.id,
'first_name' => 'firstname'
}
end
context 'with a single successful job' do
subject { create(:form526_submission, :with_one_succesful_job) }
it 'sets the submission.complete to true' do
expect(subject.workflow_complete).to be_falsey
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
subject.reload
expect(subject.workflow_complete).to be_truthy
end
end
context 'with multiple successful jobs' do
subject { create(:form526_submission, :with_multiple_succesful_jobs) }
it 'sets the submission.complete to true' do
expect(subject.workflow_complete).to be_falsey
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
subject.reload
expect(subject.workflow_complete).to be_truthy
end
end
context 'with multiple successful jobs and email and submitted time in PM' do
subject { create(:form526_submission, :with_multiple_succesful_jobs, submitted_claim_id: 123_654_879) }
before { Timecop.freeze(Time.zone.parse('2012-07-20 14:15:00 UTC')) }
after { Timecop.return }
it 'calls confirmation email job with correct personalization' do
allow(Form526ConfirmationEmailJob).to receive(:perform_async) do |*args|
expect(args[0]['first_name']).to eql('firstname')
expect(args[0]['submitted_claim_id']).to be(123_654_879)
expect(args[0]['email']).to eql('test@email.com')
expect(args[0]['date_submitted']).to eql('July 20, 2012 2:15 p.m. UTC')
end
subject.workflow_complete_handler(nil, options)
end
end
context 'with multiple successful jobs and email and submitted time in PM with two digit hour' do
subject { create(:form526_submission, :with_multiple_succesful_jobs, submitted_claim_id: 123_654_879) }
before { Timecop.freeze(Time.zone.parse('2012-07-20 11:12:00 UTC')) }
after { Timecop.return }
it 'calls confirmation email job with correct personalization' do
allow(Form526ConfirmationEmailJob).to receive(:perform_async) do |*args|
expect(args[0]['first_name']).to eql('firstname')
expect(args[0]['submitted_claim_id']).to be(123_654_879)
expect(args[0]['email']).to eql('test@email.com')
expect(args[0]['date_submitted']).to eql('July 20, 2012 11:12 a.m. UTC')
end
subject.workflow_complete_handler(nil, options)
end
end
context 'with multiple successful jobs and email and submitted time in morning' do
subject { create(:form526_submission, :with_multiple_succesful_jobs, submitted_claim_id: 123_654_879) }
before { Timecop.freeze(Time.zone.parse('2012-07-20 8:07:00 UTC')) }
after { Timecop.return }
it 'calls confirmation email job with correct personalization' do
allow(Form526ConfirmationEmailJob).to receive(:perform_async) do |*args|
expect(args[0]['first_name']).to eql('firstname')
expect(args[0]['submitted_claim_id']).to be(123_654_879)
expect(args[0]['email']).to eql('test@email.com')
expect(args[0]['date_submitted']).to eql('July 20, 2012 8:07 a.m. UTC')
end
subject.workflow_complete_handler(nil, options)
end
end
context 'with submission confirmation email when successful job statuses' do
subject { create(:form526_submission, :with_multiple_succesful_jobs) }
it 'does not trigger job when disability_526_call_received_email_from_polling enabled' do
Flipper.enable(:disability_526_call_received_email_from_polling)
expect do
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
end.not_to change(Form526ConfirmationEmailJob.jobs, :size)
end
it 'returns one job triggered when disability_526_call_received_email_from_polling disabled' do
Flipper.disable(:disability_526_call_received_email_from_polling)
expect do
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
end.to change(Form526ConfirmationEmailJob.jobs, :size).by(1)
end
end
end
describe 'failure' do
context 'with mixed result jobs' do
subject { create(:form526_submission, :with_mixed_status) }
it 'sets the submission.complete to true' do
expect(subject.workflow_complete).to be_falsey
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
subject.reload
expect(subject.workflow_complete).to be_falsey
end
end
context 'with a failing 526 form job' do
subject { create(:form526_submission, :with_one_failed_job) }
it 'sets the submission.complete to true' do
expect(subject.workflow_complete).to be_falsey
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
subject.reload
expect(subject.workflow_complete).to be_falsey
end
end
context 'with submission confirmation email when failed job statuses' do
subject { create(:form526_submission, :with_mixed_status) }
it 'returns zero jobs triggered' do
expect do
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
end.not_to change(Form526ConfirmationEmailJob.jobs, :size)
end
end
it 'sends a submission failed email notification' do
expect do
subject.workflow_complete_handler(nil, 'submission_id' => subject.id)
end.to change(Form526SubmissionFailedEmailJob.jobs, :size).by(1)
end
end
end
describe '#disabilities_not_service_connected?' do
subject { form_526_submission.disabilities_not_service_connected? }
let(:icn) { '123498767V234859' }
let(:form_526_submission) do
Form526Submission.create(
user_uuid: user.uuid,
user_account:,
saved_claim_id: saved_claim.id,
auth_headers_json: auth_headers.to_json,
form_json: File.read("spec/support/disability_compensation_form/submissions/#{form_json_filename}")
)
end
context 'Lighthouse provider' do
before do
VCR.insert_cassette('lighthouse/veteran_verification/disability_rating/200_Not_Connected_response')
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('blahblech')
end
after do
VCR.eject_cassette('lighthouse/veteran_verification/disability_rating/200_Not_Connected_response')
end
context 'when all corresponding rated disabilities are not service-connected' do
let(:form_json_filename) { 'only_526_asthma.json' }
it 'returns true' do
expect(subject).to be_truthy
end
end
context 'when some but not all corresponding rated disabilities are not service-connected' do
let(:form_json_filename) { 'only_526_two_rated_disabilities.json' }
it 'returns false' do
expect(subject).to be_falsey
end
end
context 'when some disabilities do not have a ratedDisabilityId yet' do
let(:form_json_filename) { 'only_526_mixed_action_disabilities.json' }
it 'returns false' do
expect(subject).to be_falsey
end
end
end
end
describe '#cfi_checkbox_was_selected?' do
subject { form_526_submission.cfi_checkbox_was_selected? }
let!(:in_progress_form) { create(:in_progress_526_form, user_uuid: user.uuid) }
let(:form_526_submission) do
Form526Submission.create(
user_uuid: user.uuid,
user_account: user.user_account,
saved_claim_id: saved_claim.id,
auth_headers_json: auth_headers.to_json,
form_json: File.read('spec/support/disability_compensation_form/submissions/only_526_tinnitus.json')
)
end
context 'when associated with a default InProgressForm' do
it 'returns false' do
expect(subject).to be_falsey
end
end
context 'when associated with a InProgressForm that went through CFI being selected' do
let(:params) do
{ form_data: { 'view:claim_type' => { 'view:claiming_increase' => true } } }
end
it 'returns true' do
ClaimFastTracking::MaxCfiMetrics.log_form_update(in_progress_form, params)
in_progress_form.update!(params)
expect(subject).to be_truthy
end
end
end
describe '#remediated?' do
context 'when there are no form526_submission_remediations' do
it 'returns false' do
expect(subject).not_to be_remediated
end
end
context 'when there are form526_submission_remediations' do
let(:remediation) do
create(:form526_submission_remediation, form526_submission: subject)
end
it 'returns true if the most recent remediation was successful' do
remediation.update(success: true)
expect(subject).to be_remediated
end
it 'returns false if the most recent remediation was not successful' do
remediation.update(success: false)
expect(subject).not_to be_remediated
end
end
end
describe '#duplicate?' do
context 'when there are no form526_submission_remediations' do
it 'returns false' do
expect(subject).not_to be_duplicate
end
end
context 'when there are form526_submission_remediations' do
let(:remediation) do
create(:form526_submission_remediation, form526_submission: subject)
end
it 'returns true if the most recent remediation_type is ignored_as_duplicate' do
remediation.update(remediation_type: :ignored_as_duplicate)
expect(subject).to be_duplicate
end
it 'returns false if the most recent remediation_type is not ignored_as_duplicate' do
remediation.update(remediation_type: :manual)
expect(subject).not_to be_duplicate
end
end
end
describe '#success_type?' do
let(:remediation) do
create(:form526_submission_remediation, form526_submission: subject)
end
context 'when submitted_claim_id is present and backup_submitted_claim_status is nil' do
subject { create(:form526_submission, :with_submitted_claim_id) }
it 'returns true' do
expect(subject).to be_success_type
end
end
context 'when backup_submitted_claim_id is present and backup_submitted_claim_status is accepted' do
subject { create(:form526_submission, :backup_path, :backup_accepted) }
it 'returns true' do
expect(subject).to be_success_type
end
end
context 'when the most recent remediation is successful' do
it 'returns true' do
remediation.update(success: true)
expect(subject).to be_success_type
end
end
context 'when none of the success conditions are met' do
it 'returns false' do
remediation.update(success: false)
expect(subject).not_to be_success_type
end
end
end
describe '#in_process?' do
context 'when submitted_claim_id and backup_submitted_claim_status are both nil' do
context 'and the record was created within the last 3 days' do
it 'returns true' do
expect(subject).to be_in_process
end
end
context 'and the record was created more than 3 weeks ago' do
subject { create(:form526_submission, :created_more_than_3_weeks_ago) }
it 'returns false' do
expect(subject).not_to be_in_process
end
end
end
context 'when submitted_claim_id is not nil' do
subject { create(:form526_submission, :with_submitted_claim_id) }
it 'returns false' do
expect(subject).not_to be_in_process
end
end
context 'when backup_submitted_claim_status is not nil' do
subject { create(:form526_submission, :backup_path, :backup_accepted) }
it 'returns false' do
expect(subject).not_to be_in_process
end
end
end
describe '#failure_type?' do
context 'when the submission is a success type' do
subject { create(:form526_submission, :with_submitted_claim_id) }
it 'returns true' do
expect(subject).not_to be_failure_type
end
end
context 'when the submission is in process' do
it 'returns false' do
expect(subject).not_to be_failure_type
end
end
context 'when the submission is neither a success type nor in process' do
subject { create(:form526_submission, :created_more_than_3_weeks_ago) }
it 'returns true' do
expect(subject).to be_failure_type
end
end
end
describe 'ICN retrieval' do
let(:user) { create(:user, :loa3) }
let(:auth_headers) do
EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h)
end
let(:submission) do
create(:form526_submission,
user_uuid: user.uuid,
auth_headers_json: auth_headers.to_json,
saved_claim_id: saved_claim.id)
end
let!(:form526_submission) { create(:form526_submission) }
let(:expected_log_payload) { { user_uuid: user.uuid, submission_id: submission.id } }
context 'when the submission includes a UserAccount with an ICN, as expected' do
it 'uses the submission\'s user account ICN' do
submission.user_account = UserAccount.new(icn: '123498767V222222')
account = submission.account
expect(account.icn).to eq('123498767V222222')
end
end
context 'when the submission does not have a UserAccount with an ICN' do
let(:mpi_profile) { build(:mpi_profile) }
let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) }
let(:edipi_profile_response) { mpi_profile_response }
let(:no_user_account_icn_message) { 'Form526Submission::account - no UserAccount ICN found' }
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_edipi).and_return(edipi_profile_response)
end
it 'uses the auth_headers EDIPI to look up account information from MPI' do
submission.user_account = UserAccount.create!(icn: nil)
submission.save!
expect(Rails.logger).to receive(:info).with(no_user_account_icn_message, expected_log_payload)
expect_any_instance_of(MPI::Service).to receive(:find_profile_by_edipi).with(edipi: user.edipi)
account = submission.account
expect(account.icn).to eq(mpi_profile.icn)
end
context 'when the MPI lookup by EDIPI fails' do
let(:edipi_profile_response) { create(:find_profile_not_found_response) }
let(:attributes_profile_response) { mpi_profile_response }
let(:no_mpi_by_edipi_message) { 'Form526Submission::account - unable to look up MPI profile with EDIPI' }
before do
allow(Rails.logger).to receive(:info).with(no_user_account_icn_message,
expected_log_payload).and_call_original
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes)
.and_return(attributes_profile_response)
end
it 'uses the auth_headers user attributes to look up account information from MPI' do
submission.user_account = UserAccount.create!(icn: nil)
submission.save!
expect(Rails.logger).to receive(:info).with(no_mpi_by_edipi_message, expected_log_payload)
expect_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes).with(
first_name: user.first_name,
last_name: user.last_name,
ssn: user.ssn,
birth_date: user.birth_date
)
account = submission.account
expect(account.icn).to eq(mpi_profile.icn)
end
context 'when the MPI lookup by attributes fails' do
let(:attributes_profile_response) { create(:find_profile_not_found_response) }
let(:no_icn_found_message) { 'Form526Submission::account - no ICN present' }
before do
allow(Rails.logger).to receive(:info).with(no_user_account_icn_message,
expected_log_payload).and_call_original
allow(Rails.logger).to receive(:info).with(no_mpi_by_edipi_message, expected_log_payload).and_call_original
end
it 'does not return a UserAccount with an ICN' do
submission.user_account = UserAccount.create!(icn: nil)
submission.save!
expect_any_instance_of(MPI::Service).to receive(:find_profile_by_edipi).with(edipi: user.edipi)
expect_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes).with(
first_name: user.first_name,
last_name: user.last_name,
ssn: user.ssn,
birth_date: user.birth_date
)
expect(Rails.logger).to receive(:info).with(no_icn_found_message, expected_log_payload)
account = submission.account
expect(account.icn).to be_nil
end
end
end
end
end
describe '#submit_uploads' do
let(:form526_submission) { Form526Submission.new(id: 123, form_json:) }
let(:uploads) do
[
{ 'name' => 'file1.pdf', 'size' => 100 },
{ 'name' => 'file2.pdf', 'size' => 200 },
{ 'name' => 'file1.pdf', 'size' => 100 } # duplicate
]
end
let(:form_json) do
{
Form526Submission::FORM_526_UPLOADS => uploads
}.to_json
end
before do
allow(form526_submission).to receive(:form).and_return(JSON.parse(form_json))
allow(StatsD).to receive(:gauge)
allow(EVSS::DisabilityCompensationForm::SubmitUploads).to receive(:perform_in)
allow(form526_submission).to receive(:calc_submit_delays).and_return(60, 120, 180)
end
context 'when uploads are present' do
it 'sends the count of uploads to StatsD' do
form526_submission.submit_uploads
expect(StatsD).to have_received(:gauge).with('form526.uploads.count', 3,
tags: ["form_id:#{Form526Submission::FORM_526}"])
end
it 'sends the count of duplicate uploads to StatsD' do
form526_submission.submit_uploads
expect(StatsD).to have_received(:gauge).with('form526.uploads.duplicates', 1,
tags: ["form_id:#{Form526Submission::FORM_526}"])
end
it 'queues a job for each upload with the correct delay' do
form526_submission.submit_uploads
expect(EVSS::DisabilityCompensationForm::SubmitUploads).to have_received(:perform_in).with(60, 123, uploads[0])
expect(EVSS::DisabilityCompensationForm::SubmitUploads).to have_received(:perform_in).with(120, 123, uploads[1])
expect(EVSS::DisabilityCompensationForm::SubmitUploads).to have_received(:perform_in).with(180, 123, uploads[2])
end
it 'sends the delay to StatsD for each upload' do
form526_submission.submit_uploads
expect(StatsD).to have_received(:gauge).with('form526.uploads.delay', 60, tags: anything)
expect(StatsD).to have_received(:gauge).with('form526.uploads.delay', 120, tags: anything)
expect(StatsD).to have_received(:gauge).with('form526.uploads.delay', 180, tags: anything)
end
end
context 'when uploads are blank' do
let(:uploads) { [] }
it 'sends the count of uploads to StatsD and returns early' do
expect(EVSS::DisabilityCompensationForm::SubmitUploads).not_to receive(:perform_in)
form526_submission.submit_uploads
expect(StatsD).to have_received(:gauge).with('form526.uploads.count', 0,
tags: ["form_id:#{Form526Submission::FORM_526}"])
end
end
end
context 'Upload document type metrics logging' do
let!(:in_progress_form) do
ipf = create(:in_progress_526_form, user_uuid: user.uuid)
fd = ipf.form_data
fd = JSON.parse(fd)
fd['privateMedicalRecordAttachments'] = private_medical_record_attachments
fd['additionalDocuments'] = additional_documents
ipf.update!(form_data: fd)
ipf
end
let(:private_medical_record_attachments) { [] }
let(:additional_documents) { [] }
before do
allow(StatsD).to receive(:increment)
allow(Rails.logger).to receive(:info)
end
def expect_log_statement(additional_docs_by_type, private_medical_docs_by_type)
return if additional_docs_by_type.blank? && private_medical_docs_by_type.blank?
expect(Rails.logger).to have_received(:info).with(
'Form526 evidence document type metrics',
{
id: subject.id,
additional_docs_by_type:,
private_medical_docs_by_type:
}
)
end
def expect_documents_metrics(group_name, docs_by_type)
return if docs_by_type.blank?
docs_by_type.each do |type, count|
expect(StatsD).to have_received(:increment).with(
"worker.document_type_metrics.#{group_name}_document_type",
count,
tags: ["document_type:#{type}", 'source:form526']
)
end
end
context 'when form data has no documents' do
it 'logs empty document type breakdowns' do
subject.start
expect(Rails.logger).not_to have_received(:info).with(
'Form526 evidence document type metrics',
anything
)
end
end
context 'when form data has empty documents element' do
let(:additional_documents) { [{}] }
it 'logs empty document type breakdowns' do
subject.start
expect(Rails.logger).not_to have_received(:info).with(
'Form526 evidence document type metrics',
anything
)
end
end
context 'when form data has unexpected documents element' do
let(:additional_documents) { ["something's up"] }
it 'logs empty document type breakdowns' do
subject.start
expect_log_statement({ 'unknown' => 1 }, {})
expect_documents_metrics('additional_documents', { 'unknown' => 1 })
expect_documents_metrics('private_medical_record_attachments', {})
end
end
context 'when form data has additional documents' do
let(:additional_documents) do
[
{ 'name' => 'doc1', 'attachmentId' => 'type1' },
{ 'name' => 'doc2', 'attachmentId' => 'type2' },
{ 'name' => 'doc3', 'attachmentId' => 'type2' }
]
end
it 'logs document type metrics for additional documents' do
subject.start
expect_log_statement({ 'type1' => 1, 'type2' => 2 }, {})
expect_documents_metrics('additional_documents', { 'type1' => 1, 'type2' => 2 })
expect_documents_metrics('private_medical_record_attachments', {})
end
end
context 'when form data has private medical records' do
let(:private_medical_record_attachments) do
[
{ 'name' => 'doc1', 'attachmentId' => 'type3' },
{ 'name' => 'doc2', 'attachmentId' => 'type3' },
{ 'name' => 'doc3', 'attachmentId' => 'type4' }
]
end
it 'logs document type metrics for private medical records' do
subject.start
expect_log_statement({}, { 'type3' => 2, 'type4' => 1 })
expect_documents_metrics('additional_documents', {})
expect_documents_metrics('private_medical_record_attachments', { 'type3' => 2, 'type4' => 1 })
end
end
context 'when form data has both additional documents and private medical records' do
let(:additional_documents) do
[
{ 'name' => 'doc1', 'attachmentId' => 'type1' },
{ 'name' => 'doc2', 'attachmentId' => 'type2' },
{ 'name' => 'doc3', 'attachmentId' => 'type2' }
]
end
let(:private_medical_record_attachments) do
[
{ 'name' => 'doc4', 'attachmentId' => 'type3' },
{ 'name' => 'doc5', 'attachmentId' => 'type3' },
{ 'name' => 'doc6', 'attachmentId' => 'type4' }
]
end
it 'logs summary metrics with document type breakdowns' do
subject.start
expect_log_statement({ 'type1' => 1, 'type2' => 2 }, { 'type3' => 2, 'type4' => 1 })
expect_documents_metrics('additional_documents', { 'type1' => 1, 'type2' => 2 })
expect_documents_metrics('private_medical_record_attachments', { 'type3' => 2, 'type4' => 1 })
end
end
context 'when documents have no attachmentId' do
let(:additional_documents) do
[
{ 'name' => 'doc1' },
{ 'name' => 'doc2' }
]
end
let(:private_medical_record_attachments) do
[
{ 'name' => 'doc3' }
]
end
it 'uses "unknown" as the attachment type' do
subject.start
expect_log_statement({ 'unknown' => 2 }, { 'unknown' => 1 })
expect_documents_metrics('additional_documents', { 'unknown' => 2 })
expect_documents_metrics('private_medical_record_attachments', { 'unknown' => 1 })
end
end
end
describe '#log_error' do
let(:error) { StandardError.new('Test error message') }
it 'logs an error message with submission ID and error details' do
expect(Rails.logger).to receive(:error).with(
"Form526ClaimsFastTrackingConcern #{subject.id} encountered an error",
submission_id: subject.id,
error_message: 'Test error message'
)
subject.send(:log_error, error)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/iam_user_identity_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe IAMUserIdentity, type: :model do
let(:idme_attrs) { build(:idme_loa3_introspection_payload) }
let(:dslogon_attrs) { build(:dslogon_level2_introspection_payload) }
let(:mhv_attrs) { build(:mhv_premium_introspection_payload) }
let(:logingov_attrs) { build(:logingov_ial2_introspection_payload) }
context 'for a Login.gov user' do
it 'returns IAL2 for a premium assurance level' do
id = described_class.build_from_iam_profile(logingov_attrs)
expect(id.loa[:current]).to eq(3)
end
it 'returns multifactor as true' do # all login.gov users are forced to use MFA
id = described_class.build_from_iam_profile(logingov_attrs)
expect(id.multifactor).to be(true)
end
end
context 'for an ID.me user' do
it 'returns LOA3 for a premium assurance level' do
id = described_class.build_from_iam_profile(idme_attrs)
expect(id.loa[:current]).to eq(3)
end
it 'returns multifactor as true' do
id = described_class.build_from_iam_profile(idme_attrs)
expect(id.multifactor).to be(true)
end
end
context 'for a DSLogon user' do
it 'returns LOA3 for a premium assurance level' do
id = described_class.build_from_iam_profile(dslogon_attrs)
expect(id.loa[:current]).to eq(3)
end
it 'returns multifactor as false' do
id = described_class.build_from_iam_profile(dslogon_attrs)
expect(id.multifactor).to be(false)
end
end
context 'for an MHV user' do
it 'returns LOA3 for a premium assurance level' do
id = described_class.build_from_iam_profile(mhv_attrs)
expect(id.loa[:current]).to eq(3)
end
it 'returns multifactor as false' do
id = described_class.build_from_iam_profile(mhv_attrs)
expect(id.multifactor).to be(false)
end
end
context 'with multiple MHV IDs' do
it 'plucks the first value' do
attrs = mhv_attrs.merge(fediam_mhv_ien: '123456,7890123')
id = described_class.build_from_iam_profile(attrs)
expect(id.iam_mhv_id).to eq('123456')
end
it 'logs a warning to Rails logger' do
attrs = mhv_attrs.merge(fediam_mhv_ien: '123456,7890123')
expect(Rails.logger).to receive(:warn).with(
'[IAMUserIdentity] OAuth: Multiple MHV IDs present',
mhv_ien: '123456,7890123'
)
described_class.build_from_iam_profile(attrs)
end
it 'ignores non-unique duplicates' do
attrs = mhv_attrs.merge(fediam_mhv_ien: '123456,123456')
expect(Sentry).not_to receive(:capture_message)
id = described_class.build_from_iam_profile(attrs)
expect(id.iam_mhv_id).to eq('123456')
end
end
context 'with no MHV ID' do
it 'parses reserved value correctly' do
attrs = mhv_attrs.merge(fediam_mhv_ien: 'NOT_FOUND')
id = described_class.build_from_iam_profile(attrs)
expect(id.iam_mhv_id).to be_nil
end
end
context 'with a user who has a found EDIPI' do
it 'returns edipi number' do
id = described_class.build_from_iam_profile(idme_attrs)
expect(id.iam_edipi).to eq('1005079124')
end
end
context 'with a user who has a not found EDIPI' do
it 'returns nil' do
id = described_class.build_from_iam_profile(mhv_attrs)
expect(id.iam_edipi).to be_nil
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/lighthouse_document_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe LighthouseDocument do
describe 'validations' do
describe '#convert_to_unlock_pdf' do
let(:tracked_item_id) { 33 }
let(:document_type) { 'L023' }
let(:file_name) { 'locked_pdf_password_is_test.pdf' }
let(:bad_password) { 'bad_pw' }
context 'when provided password is incorrect' do
shared_examples 'logs a sanitized error message' do
it 'logs a sanitized message without sensitive data' do
error_message = nil
allow_any_instance_of(Vets::SharedLogging).to receive(:log_exception_to_rails) do |_, error, _level|
error_message = error.message
end
tempfile = Tempfile.new(['', "-#{file_name}"])
file_obj = ActionDispatch::Http::UploadedFile.new(
original_filename: file_name,
type: 'application/pdf',
tempfile:
)
document = LighthouseDocument.new(
file_obj:,
file_name:,
tracked_item_id:,
document_type:,
password: bad_password
)
expect(document).not_to be_valid
expect(error_message).not_to include(file_name)
expect(error_message).not_to include(bad_password)
end
end
context 'pdftk' do
before do
allow(Flipper).to receive(:enabled?)
.with(:lighthouse_document_convert_to_unlocked_pdf_use_hexapdf)
.and_return(false)
end
it_behaves_like 'logs a sanitized error message'
end
context 'hexapdf' do
before do
allow(Flipper).to receive(:enabled?)
.with(:lighthouse_document_convert_to_unlocked_pdf_use_hexapdf)
.and_return(true)
end
it_behaves_like 'logs a sanitized error message'
end
end
end
end
describe '#to_serializable_hash' do
it 'does not return file_obj' do
f = Tempfile.new(['file with spaces', '.txt'])
f.write('test')
f.rewind
rack_file = Rack::Test::UploadedFile.new(f.path, 'text/plain')
upload_file = ActionDispatch::Http::UploadedFile.new(
tempfile: rack_file.tempfile,
filename: rack_file.original_filename,
type: rack_file.content_type
)
document = EVSSClaimDocument.new(
evss_claim_id: 1,
tracked_item_id: 1,
file_obj: upload_file,
file_name: File.basename(upload_file.path)
)
expect(document.to_serializable_hash.keys).not_to include(:file_obj)
expect(document.to_serializable_hash.keys).not_to include('file_obj')
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/dependents_application_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DependentsApplication, type: :model do
let(:dependents_application) { create(:dependents_application) }
describe '.filter_children' do
it 'filters children to match dependents' do
dependents = [
{
'childSocialSecurityNumber' => '111223333'
}
]
children = [
{
'ssn' => '111-22-3334'
},
{
'ssn' => '111-22-3333'
}
]
expect(described_class.filter_children(dependents, children)).to eq(
[{ 'ssn' => '111-22-3333' }]
)
end
end
describe '#user_can_access_evss' do
it 'does not allow users who dont have evss access' do
dependents_application = DependentsApplication.new(user: create(:user))
expect_attr_invalid(dependents_application, :user, 'must have evss access')
end
it 'allows evss users' do
dependents_application = DependentsApplication.new(user: create(:evss_user))
expect_attr_valid(dependents_application, :user)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/rate_limited_search_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe RateLimitedSearch do
describe '#create_or_increment_count' do
let(:params) { '1234' }
let(:hashed_params) { Digest::SHA2.hexdigest(params) }
context 'when an existing search doesnt exist' do
it 'creates a new model' do
described_class.create_or_increment_count(params)
expect(described_class.find(hashed_params).count).to eq(1)
end
end
context 'when an existing search exists' do
let!(:rate_limited_search) { create(:rate_limited_search) }
it 'increments the count' do
described_class.create_or_increment_count(params)
expect(described_class.find(hashed_params).count).to eq(2)
end
context 'when an existing search exists with max count' do
it 'raises a rate limited error' do
rate_limited_search.count = 3
rate_limited_search.save!
expect do
described_class.create_or_increment_count(params)
end.to raise_error(RateLimitedSearch::RateLimitedError)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/lcpe_redis_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe LCPERedis do
subject { LCPERedis.new(lcpe_type:) }
let(:lcpe_type) { 'lacs' }
let(:v_fresh) { '3' }
let(:v_stale) { '2' }
let(:response_headers) { { 'Etag' => "W/\"#{v_fresh}\"" } }
let(:raw_response) { generate_response_double(200) }
let(:cached_response) { GI::LCPE::Response.from(generate_response_double(200)) }
def generate_response_double(status, headers = response_headers)
double('FaradayResponse', body: { lacs: [] }, status:, response_headers: headers)
end
describe '.initialize' do
it 'requires lcpe_type kwarg and sets attribute' do
expect(subject.lcpe_type).to eq(lcpe_type)
end
end
describe '#fresh_version_from' do
context 'when GIDS response not modified' do
let(:raw_response) { generate_response_double(304) }
before { LCPERedis.new.cache(lcpe_type, cached_response) }
it 'returns cached response' do
expect(described_class).not_to receive(:delete)
expect(subject.fresh_version_from(raw_response).version).to eq(cached_response.version)
end
end
context 'when GIDS response modified' do
context 'when status 200' do
before { allow(GI::LCPE::Response).to receive(:from).with(raw_response).and_return(cached_response) }
it 'invalidates cache and caches new response' do
expect(described_class).to receive(:delete).with(lcpe_type)
expect(cached_response).to receive(:cache?).and_return(true)
expect(subject.fresh_version_from(raw_response).version).to eq(cached_response.version)
end
end
end
end
describe '#force_client_refresh_and_cache' do
before { LCPERedis.new.cache(lcpe_type, cached_response) }
context 'when redis cache stale' do
let(:stale_headers) { { 'Etag' => "W/\"#{v_stale}\"" } }
let(:cached_response) { GI::LCPE::Response.from(generate_response_double(200, stale_headers)) }
it 'caches gids response and raises error' do
expect { subject.force_client_refresh_and_cache(raw_response) }
.to change { LCPERedis.find(lcpe_type).response.version }.from(v_stale).to(v_fresh)
.and raise_error(LCPERedis::ClientCacheStaleError)
end
end
context 'when redis cache fresh' do
it 'raises error without caching response' do
expect { subject.force_client_refresh_and_cache(raw_response) }
.to not_change { LCPERedis.find(lcpe_type).response.version }
.and raise_error(LCPERedis::ClientCacheStaleError)
end
end
end
describe '#cached_response' do
context 'when cache nil' do
it 'returns nil' do
expect(subject.cached_response).to be_nil
end
end
context 'when cache present' do
before { LCPERedis.new.cache(lcpe_type, cached_response) }
it 'returns cached response' do
expect(subject.cached_response).to be_a GI::LCPE::Response
end
end
end
describe '#cached_version' do
context 'when cache nil' do
it 'returns nil' do
expect(subject.cached_version).to be_nil
end
end
context 'when cache present' do
before { LCPERedis.new.cache(lcpe_type, cached_response) }
it 'returns cached version' do
expect(subject.cached_version).to eq(cached_response.version)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/ivc_champva_forms_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe IvcChampvaForm, type: :model do
describe 'validations' do
it { is_expected.to validate_presence_of(:form_uuid) }
context 'when form_uuid is missing' do
it 'is invalid' do
form = build(:ivc_champva_form, form_uuid: nil)
expect(form).not_to be_valid
expect(form.errors[:form_uuid]).to include("can't be blank")
end
end
end
describe 'factory' do
it 'is valid' do
expect(build(:ivc_champva_form)).to be_valid
end
end
describe 'methods' do
describe '#create' do
it 'creates a new form' do
expect { create(:ivc_champva_form) }.to change(IvcChampvaForm, :count).by(1)
end
end
describe '#update' do
let(:form) { create(:ivc_champva_form) }
it 'updates an existing form' do
new_email = 'new_email@example.com'
form.update(email: new_email)
expect(form.reload.email).to eq(new_email)
end
end
describe '#destroy' do
let!(:form) { create(:ivc_champva_form) }
it 'deletes an existing form' do
expect { form.destroy }.to change(IvcChampvaForm, :count).by(-1)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/triage_team_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe TriageTeam do
context 'with valid attributes' do
subject { described_class.new(params) }
let(:params) { attributes_for(:triage_team, triage_team_id: 100, preferred_team: true) }
let(:other) { described_class.new(attributes_for(:triage_team, triage_team_id: 101)) }
it 'populates attributes' do
expect(described_class.attribute_set).to contain_exactly(:triage_team_id, :name, :relation_type,
:preferred_team)
expect(subject.triage_team_id).to eq(params[:triage_team_id])
expect(subject.name).to eq(params[:name])
expect(subject.relation_type).to eq(params[:relation_type])
expect(subject.preferred_team).to be(true)
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
|
code_files/vets-api-private/spec/models/form_submission_attempt_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormSubmissionAttempt, type: :model do
describe 'associations' do
it { is_expected.to belong_to(:form_submission) }
end
describe 'state machine' do
before { allow_any_instance_of(SimpleFormsApi::Notification::Email).to receive(:send) }
let(:config) do
{
form_data: anything,
form_number: anything,
date_submitted: anything,
lighthouse_updated_at: anything,
confirmation_number: anything
}
end
context 'transitioning to a failure state' do
let(:notification_type) { :error }
context 'is a simple form' do
let(:form_submission) { build(:form_submission, form_type: '21-4142') }
let(:form_submission_attempt) { create(:form_submission_attempt, form_submission:) }
it 'transitions to a failure state' do
expect(form_submission_attempt)
.to transition_from(:pending).to(:failure).on_event(:fail)
end
it 'enqueues an error email' do
allow(SimpleFormsApi::Notification::SendNotificationEmailJob).to receive(:perform_async)
form_submission_attempt.fail!
expect(SimpleFormsApi::Notification::SendNotificationEmailJob).to have_received(:perform_async).with(
form_submission_attempt.benefits_intake_uuid,
'vba_21_4142'
)
end
end
context 'is not a simple form' do
let(:form_submission) { build(:form_submission, form_type: 'some-other-form') }
it 'does not send an error email' do
allow(SimpleFormsApi::Notification::Email).to receive(:new)
form_submission_attempt = create(:form_submission_attempt, form_submission:)
form_submission_attempt.fail!
expect(SimpleFormsApi::Notification::Email).not_to have_received(:new)
end
context 'is a form526_form4142 form' do
let(:vanotify_client) { instance_double(VaNotify::Service) }
let!(:email_klass) { EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail }
let!(:form526_submission) { create(:form526_submission) }
let!(:form526_form4142_form_submission) do
create(:form_submission, saved_claim_id: form526_submission.saved_claim_id,
form_type: CentralMail::SubmitForm4142Job::FORM4142_FORMSUBMISSION_TYPE)
end
let!(:form_submission_attempt) do
FormSubmissionAttempt.create(form_submission: form526_form4142_form_submission)
end
it 'sends an 4142 error email when it is not a SimpleFormsApi form and flippers are on' do
Flipper.enable(CentralMail::SubmitForm4142Job::POLLING_FLIPPER_KEY)
Flipper.enable(CentralMail::SubmitForm4142Job::POLLED_FAILURE_EMAIL)
allow(VaNotify::Service).to receive(:new).and_return(vanotify_client)
allow(vanotify_client).to receive(:send_email).and_return(OpenStruct.new(id: 'some_id'))
with_settings(Settings.vanotify.services.benefits_disability, { api_key: 'test_service_api_key' }) do
expect do
form_submission_attempt.fail!
email_klass.drain
end.to trigger_statsd_increment("#{email_klass::STATSD_METRIC_PREFIX}.success")
.and change(Form526JobStatus, :count).by(1)
job_tracking = Form526JobStatus.last
expect(job_tracking.form526_submission_id).to eq(form526_submission.id)
expect(job_tracking.job_class).to eq(email_klass.class_name)
end
end
it 'does not send an 4142 error email when it is not a SimpleFormsApi form and flippers are off' do
Flipper.disable(CentralMail::SubmitForm4142Job::POLLING_FLIPPER_KEY)
Flipper.disable(CentralMail::SubmitForm4142Job::POLLED_FAILURE_EMAIL)
with_settings(Settings.vanotify.services.benefits_disability, { api_key: 'test_service_api_key' }) do
expect do
form_submission_attempt.fail!
email_klass.drain
end.to not_trigger_statsd_increment("#{email_klass::STATSD_METRIC_PREFIX}.success")
.and not_change(Form526JobStatus, :count)
end
end
end
end
end
it 'transitions to a success state' do
form_submission_attempt = create(:form_submission_attempt)
expect(form_submission_attempt)
.to transition_from(:pending).to(:success).on_event(:succeed)
end
it 'transitions to a manual state' do
form_submission_attempt = create(:form_submission_attempt)
expect(form_submission_attempt)
.to transition_from(:failure).to(:manually).on_event(:manual)
end
context 'transitioning to a vbms state' do
let(:notification_type) { :received }
it 'transitions to a vbms state' do
form_submission_attempt = create(:form_submission_attempt)
expect(form_submission_attempt)
.to transition_from(:pending).to(:vbms).on_event(:vbms)
end
it 'sends a received email' do
allow(SimpleFormsApi::Notification::SendNotificationEmailJob).to receive(:perform_async)
form_submission_attempt = create(:form_submission_attempt)
form_submission_attempt.vbms!
expect(SimpleFormsApi::Notification::SendNotificationEmailJob).to have_received(:perform_async).with(
form_submission_attempt.benefits_intake_uuid,
'vba_21_4142'
)
end
end
end
describe '#log_status_change' do
it 'writes to Rails.logger.info' do
logger = double
allow(Rails).to receive(:logger).and_return(logger)
allow(logger).to receive(:info)
form_submission_attempt = create(:form_submission_attempt)
form_submission_attempt.log_status_change
expect(logger).to have_received(:info)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/spool_file_event_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SpoolFileEvent, type: :model do
subject { described_class.new }
it 'validates rpo' do
expect(described_class.new(rpo: 351).valid?).to be(true)
expect(described_class.new(rpo: 100).valid?).to be(false)
end
describe 'build_event' do
before do
SpoolFileEvent.delete_all
end
it 'returns a successful existing event' do
successful_event = create(:spool_file_event, :successful)
event = SpoolFileEvent.build_event(successful_event.rpo, successful_event.filename)
expect(successful_event.id).to eq(event.id)
expect(successful_event.rpo).to eq(event.rpo)
end
it 'returns a non-successful existing event' do
non_successful_event = create(:spool_file_event)
event = SpoolFileEvent.build_event(non_successful_event.rpo, non_successful_event.filename)
expect(non_successful_event.id).to eq(event.id)
expect(event.retry_attempt).to eq(non_successful_event.retry_attempt + 1)
end
it 'returns a new event' do
rpo = EducationForm::EducationFacility::FACILITY_IDS[:eastern]
filename = "#{rpo}_#{Time.zone.now.strftime('%m%d%Y_%H%M%S')}_vetsgov.spl"
event = SpoolFileEvent.build_event(rpo, filename)
expect(event.rpo).to eq(rpo)
expect(event.filename).to eq(filename)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/message_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Message do
context 'with valid attributes' do
subject { described_class.new(params) }
let(:params) { attributes_for(:message) }
let(:other) { described_class.new(attributes_for(:message, sent_date: Time.current)) }
it 'populates attributes' do
expect(described_class.attribute_set).to contain_exactly(:id, :category, :subject, :body,
:attachment, :attachments, :sent_date,
:sender_id, :sender_name, :recipient_id,
:recipient_name, :read_receipt, :uploads,
:suggested_name_display, :is_oh_message,
:triage_group_name, :proxy_sender_name,
:has_attachments, :attachment1_id,
:attachment2_id, :attachment3_id,
:attachment4_id, :metadata, :is_large_attachment_upload)
expect(subject.id).to eq(params[:id])
expect(subject.category).to eq(params[:category])
expect(subject.subject).to eq(params[:subject])
expect(subject.body).to eq(params[:body])
expect(subject.attachment).to eq(params[:attachment])
expect(subject.sent_date).to eq(Time.parse(params[:sent_date]).utc)
expect(subject.sender_id).to eq(params[:sender_id])
expect(subject.sender_name).to eq(params[:sender_name])
expect(subject.recipient_id).to eq(params[:recipient_id])
expect(subject.recipient_name).to eq(params[:recipient_name])
expect(subject.read_receipt).to eq(params[:read_receipt])
end
it 'sorts by sent_date DESC' do
expect([subject, other].sort).to eq([other, subject])
end
describe 'when validating' do
context 'message or draft' do
it 'requires recipient_id' do
expect(build(:message, recipient_id: '')).not_to be_valid
end
it 'requires body' do
expect(build(:message, body: '')).not_to be_valid
end
it 'requires category' do
expect(build(:message, category: '')).not_to be_valid
end
context 'file uploads' do
let(:upload_class) { 'ActionDispatch::Http::UploadedFile' }
let(:file1) { instance_double(upload_class, original_filename: 'file1.jpg', size: 1.megabyte) }
let(:file2) { instance_double(upload_class, original_filename: 'file2.jpg', size: 2.megabytes) }
let(:file3) { instance_double(upload_class, original_filename: 'file3.jpg', size: 1.megabyte) }
let(:file4) { instance_double(upload_class, original_filename: 'file4.jpg', size: 4.megabytes) }
let(:file5) { instance_double(upload_class, original_filename: 'file5.jpg', size: 6.1.megabytes) }
let(:file6) { instance_double(upload_class, original_filename: 'file6.jpg', size: 5.1.megabytes) }
before do
[file1, file2, file3, file4, file5, file6].each do |file|
allow(file).to receive(:is_a?).with(ActionDispatch::Http::UploadedFile).and_return(true)
allow(file).to receive(:is_a?).with(Hash).and_return(false)
end
end
it 'can validate file size with valid file sizes' do
message = build(:message, uploads: [file1, file2, file3, file4])
expect(message).to be_valid
end
it 'requires that there be no more than 4 uploads' do
message = build(:message, uploads: [file1, file2, file3, file4, file6])
expect(message).not_to be_valid
expect(message.errors[:base]).to include('Total file count exceeds 4 files')
end
it 'requires that upload file size not exceed 6 MB for any one file' do
message = build(:message, uploads: [file5])
expect(message).not_to be_valid
expect(message.errors[:base]).to include('The file5.jpg exceeds file size limit of 6.0 MB')
end
it 'require that total upload size not exceed 10 MB' do
message = build(:message, uploads: [file2, file3, file4, file6])
expect(message).not_to be_valid
expect(message.errors[:base]).to include('Total size of uploads exceeds 10.0 MB')
end
context 'with is_large_attachment_upload flag' do
it 'allows files up to 25 MB for large attachments' do
large_message = build(:message, is_large_attachment_upload: true, uploads: [file5])
expect(large_message).to be_valid
end
it 'rejects files over 25 MB for large attachments' do
big_large_file = instance_double(upload_class, original_filename: 'big_large_file.jpg',
size: 26.megabytes)
allow(big_large_file).to receive(:is_a?).with(ActionDispatch::Http::UploadedFile).and_return(true)
allow(big_large_file).to receive(:is_a?).with(Hash).and_return(false)
large_message = build(:message, is_large_attachment_upload: true, uploads: [big_large_file])
expect(large_message).not_to be_valid
expect(large_message.errors[:base])
.to include('The big_large_file.jpg exceeds file size limit of 25.0 MB')
end
it 'allows for more than 4 uploads and up to 10 when is_large_attachment_upload is true' do
large_message = build(:message, is_large_attachment_upload: true,
uploads: [file1, file2, file3, file4, file5, file6])
expect(large_message).to be_valid
end
it 'returns 6.0 MB for regular messages (is_large_attachment_upload = false)' do
message = build(:message, is_large_attachment_upload: false)
expect(message.send(:max_single_file_size_mb)).to eq(6.0)
end
it 'returns 6.0 MB for messages with is_large_attachment_upload = nil (default)' do
message = build(:message)
expect(message.send(:max_single_file_size_mb)).to eq(6.0)
end
it 'returns 25.0 MB for large messages (is_large_attachment_upload = true)' do
message = build(:message, is_large_attachment_upload: true)
expect(message.send(:max_single_file_size_mb)).to eq(25.0)
end
end
end
end
context 'reply' do
it 'requires recipient_id' do
expect(build(:message, recipient_id: '').as_reply).to be_valid
end
it 'requires body' do
expect(build(:message, body: '').as_reply).not_to be_valid
end
it 'requires category' do
expect(build(:message, category: '').as_reply).to be_valid
end
end
context 'drafts and replydraft' do
let(:draft_with_message) { build(:message_draft, :with_message) }
let(:draft) { build(:message_draft) }
it 'drafts must not be tied to a message' do
draft_with_message.valid?
expect(draft_with_message).not_to be_valid
end
it 'reply drafts must be tied to a message' do
expect(draft.as_reply).not_to be_valid
end
it 'requires a body' do
expect(build(:message_draft, :with_message, body: '').as_reply).not_to be_valid
end
end
end
end
context 'with file upload limits' do
let(:upload_class) { 'ActionDispatch::Http::UploadedFile' }
let(:file1) { instance_double(upload_class, original_filename: 'file1.jpg', size: 1.megabyte) }
let(:file2) { instance_double(upload_class, original_filename: 'file2.jpg', size: 2.megabytes) }
let(:file3) { instance_double(upload_class, original_filename: 'file3.jpg', size: 1.megabyte) }
let(:file4) { instance_double(upload_class, original_filename: 'file4.jpg', size: 4.megabytes) }
let(:file5) { instance_double(upload_class, original_filename: 'file5.jpg', size: 6.1.megabytes) }
before do
allow(Flipper).to receive(:enabled?).with(:mhv_secure_messaging_large_attachments).and_return(false)
[file1, file2, file3, file4, file5].each do |file|
allow(file).to receive(:is_a?).with(ActionDispatch::Http::UploadedFile).and_return(true)
allow(file).to receive(:is_a?).with(Hash).and_return(false)
end
end
it 'validates file count limit (default 4)' do
message = build(:message, uploads: [file1, file2, file3, file4, file5])
expect(message).not_to be_valid
expect(message.errors[:base]).to include('Total file count exceeds 4 files')
end
it 'validates total upload size limit (default 10MB)' do
big_file = instance_double(upload_class, original_filename: 'big.jpg', size: 11.megabytes)
allow(big_file).to receive(:is_a?).with(ActionDispatch::Http::UploadedFile).and_return(true)
allow(big_file).to receive(:is_a?).with(Hash).and_return(false)
message = build(:message, uploads: [big_file])
expect(message).not_to be_valid
expect(message.errors[:base]).to include('Total size of uploads exceeds 10.0 MB')
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form_submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormSubmission, feature: :form_submission, type: :model do
let(:user_account) { create(:user_account) }
describe 'associations' do
it { is_expected.to belong_to(:saved_claim).optional }
it { is_expected.to belong_to(:user_account).optional }
end
describe 'validations' do
it { is_expected.to validate_presence_of(:form_type) }
end
describe 'user form submission statuses' do
before do
@fsa, @fsb, @fsc = create_list(:form_submission, 3, user_account:)
.zip(%w[FORM-A FORM-B FORM-C])
.map do |submission, form_type|
submission.update(form_type:)
submission
end
@fsa1, @fsa2, @fsa3 = create_list(:form_submission_attempt, 3, form_submission: @fsa) do |attempt, index|
attempt.update(benefits_intake_uuid: SecureRandom.uuid, created_at: (3 - index).days.ago)
end
@fsb1 = create(
:form_submission_attempt,
form_submission: @fsb,
benefits_intake_uuid:
SecureRandom.uuid,
created_at: 1.day.ago
)
end
context 'when form submission has no attempts' do
it 'returns nil' do
result = FormSubmission.with_latest_benefits_intake_uuid(user_account).with_form_types(['FORM-C']).first
expect(result.benefits_intake_uuid).to be_nil
end
end
context 'when form submission has multple attempts' do
it 'returns the benefits_intake_id from the latest form submission attempt' do
result = FormSubmission.with_latest_benefits_intake_uuid(user_account).with_form_types(['FORM-A']).first
expect(result.benefits_intake_uuid).to eq(@fsa3.benefits_intake_uuid)
end
end
context 'when form submission has a single attempt with uuid' do
it 'returns the benefits_intake_id from the only form submission attempt' do
result = FormSubmission.with_latest_benefits_intake_uuid(user_account).with_form_types(['FORM-B']).first
expect(result.benefits_intake_uuid).to eq(@fsb1.benefits_intake_uuid)
end
end
context 'when form submission has a single attempt with no uuid' do
it 'returns nil' do
@fsb1.update!(benefits_intake_uuid: nil)
result = FormSubmission.with_latest_benefits_intake_uuid(user_account).with_form_types(['FORM-B']).first
expect(result.benefits_intake_uuid).to be_nil
end
end
context 'when a list of forms is provided' do
it 'returns only the records that match the given forms' do
form_types = %w[FORM-A FORM-B]
results = FormSubmission.with_latest_benefits_intake_uuid(user_account).with_form_types(form_types).to_a
expect(results.count).to eq(2)
results.each { |form| expect(form_types).to include(form.form_type) }
end
end
context 'when a list of forms is not provided' do
it 'returns all records' do
results = FormSubmission.with_form_types(nil).to_a
expect(results.count).to eq(3)
end
end
context 'latest_pending_attempt' do
it 'returns db record' do
form_submission = FormSubmission.with_form_types(nil).first
expect(form_submission.latest_pending_attempt).not_to be_nil
end
end
context 'non_failure_attempt' do
it 'returns db record' do
form_submission = FormSubmission.with_form_types(nil).first
expect(form_submission.non_failure_attempt).not_to be_nil
end
end
end
describe '#latest_attempt' do
it 'returns the newest, associated form_submission_attempt' do
form_submission = create(:form_submission, created_at: 1.day.ago)
create_list(:form_submission_attempt, 2, form_submission:, created_at: 1.day.ago)
form_submission_attempt = create(:form_submission_attempt, form_submission:)
expect(form_submission.latest_attempt).to eq form_submission_attempt
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/prescription_details_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe PrescriptionDetails do
let(:prescription_details_attributes) { attributes_for(:prescription_details) }
context 'with valid attributes' do
subject { described_class.new(prescription_details_attributes) }
it 'has attributes' do
expect(subject).to have_attributes(refill_status: 'active', refill_remaining: 9, facility_name: 'ABC1223',
is_refillable: true, is_trackable: false, prescription_id: 1_435_525,
quantity: '10', prescription_number: '2719324',
prescription_name: 'Drug 1 250MG TAB', station_number: '23',
cmop_division_phone: nil, in_cerner_transition: false,
not_refillable_display_message: 'test',
cmop_ndc_number: nil, user_id: 16_955_936, provider_first_name: 'MOHAMMAD',
provider_last_name: 'ISLAM', remarks: nil, division_name: 'DAYTON',
institution_id: nil, dial_cmop_division_phone: '',
disp_status: 'Active: Refill in Process', ndc: '00173_9447_00',
reason: nil, prescription_number_index: 'RX', prescription_source: 'RX',
disclaimer: nil, indication_for_use: nil, indication_for_use_flag: nil,
category: 'Rx Medication', tracking: false, color: nil, shape: nil,
back_imprint: nil, front_imprint: nil)
end
it 'has additional aliased rubyesque methods' do
expect(subject).to have_attributes(trackable?: false, refillable?: true)
end
it 'has date attributes' do
expect(subject).to have_attributes(refill_submit_date: Time.parse('Tue, 26 Apr 2016 00:00:00 EDT').in_time_zone,
refill_date: Time.parse('Thu, 21 Apr 2016 00:00:00 EDT').in_time_zone,
ordered_date: Time.parse('Tue, 29 Mar 2016 00:00:00 EDT').in_time_zone,
expiration_date: Time.parse('Thu, 30 Mar 2017 00:00:00 EDT').in_time_zone,
dispensed_date: Time.parse('Thu, 21 Apr 2016 00:00:00 EDT').in_time_zone,
modified_date: Time.parse('2023-08-11T15:56:58.000Z').in_time_zone)
end
it 'has method attribute sorted_dispensed_date' do
expect(subject).to have_attributes(sorted_dispensed_date: Date.parse('Thu, 21 Apr 2016'))
end
end
context 'sorted_dispensed_date test cases with dispensed_date' do
subject do
described_class.new(attributes_for(:prescription_details,
dispensed_date: Time.parse('Thu, 21 Apr 2016 00:00:00 EDT').in_time_zone,
rx_rf_records: nil))
end
it 'sorted_dispensed_date should be same as dispensed_date' do
expect(subject).to have_attributes(sorted_dispensed_date: Date.parse('Thu, 21 Apr 2016'))
end
end
context 'sorted_dispensed_date test cases with sorted_dispensed_date' do
subject { described_class.new(prescription_details_attributes) }
it 'sorted_dispensed_date should be same as sorted_dispensed_date' do
expect(subject).to have_attributes(sorted_dispensed_date: Date.parse('Thu, 21 Apr 2016'))
end
end
context 'sorted_dispensed_date test cases with nil' do
subject do
described_class.new(attributes_for(:prescription_details,
dispensed_date: nil,
rx_rf_records: [['rf_record',
[{ refill_date: 'Sat, 15 Jul 2023 00:00:00 EDT',
dispensed_date: nil }]]]))
end
it 'sorted_dispensed_date should be nil' do
expect(subject.sorted_dispensed_date).to be_nil
end
end
describe '#pharmacy_phone_number' do
context 'when cmop_division_phone is present' do
subject do
described_class.new(attributes_for(:prescription_details,
cmop_division_phone: '555-123-4567',
dial_cmop_division_phone: '555-987-6543'))
end
it 'returns cmop_division_phone' do
expect(subject.pharmacy_phone_number).to eq('555-123-4567')
end
end
context 'when only dial_cmop_division_phone is present' do
subject do
described_class.new(attributes_for(:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: '555-987-6543'))
end
it 'returns dial_cmop_division_phone' do
expect(subject.pharmacy_phone_number).to eq('555-987-6543')
end
end
context 'when phone numbers are in rx_rf_records' do
subject do
described_class.new(attributes_for(
:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: nil,
rx_rf_records: [
[
'rf_record',
[
{ cmop_division_phone: '555-111-2222' },
{ dial_cmop_division_phone: '555-333-4444' }
]
]
]
))
end
it 'returns cmop_division_phone from rx_rf_records' do
expect(subject.pharmacy_phone_number).to eq('555-111-2222')
end
end
context 'when only dial_cmop_division_phone is in rx_rf_records' do
subject do
described_class.new(attributes_for(
:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: nil,
rx_rf_records: [
[
'rf_record',
[
{ dial_cmop_division_phone: '555-333-4444' }
]
]
]
))
end
it 'returns dial_cmop_division_phone from rx_rf_records' do
expect(subject.pharmacy_phone_number).to eq('555-333-4444')
end
end
context 'when no phone numbers are available' do
subject do
described_class.new(attributes_for(
:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: nil,
rx_rf_records: []
))
end
it 'returns nil' do
expect(subject.pharmacy_phone_number).to be_nil
end
end
context 'when rx_rf_records is nil' do
subject do
described_class.new(attributes_for(
:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: nil,
rx_rf_records: nil
))
end
it 'returns nil' do
expect(subject.pharmacy_phone_number).to be_nil
end
end
context 'when rx_rf_records has empty phone numbers' do
subject do
described_class.new(attributes_for(
:prescription_details,
cmop_division_phone: nil,
dial_cmop_division_phone: nil,
rx_rf_records: [
[
'rf_record',
[
{ cmop_division_phone: '', dial_cmop_division_phone: '' }
]
]
]
))
end
it 'returns nil' do
expect(subject.pharmacy_phone_number).to be_nil
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/lighthouse526_document_upload_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Lighthouse526DocumentUpload do
# Benefts Documents API /uploads/status endpoint payload examples available at:
# https://dev-developer.va.gov/explore/api/benefits-documents/docs?version=current
it 'is created with an initial aasm status of pending' do
expect(build(:lighthouse526_document_upload).aasm_state).to eq('pending')
end
context 'for a new record' do
describe 'with valid attributes' do
it 'is valid with a valid document_type' do
['BDD Instructions', 'Form 0781', 'Form 0781a', 'Veteran Upload'].each do |document_type|
expect(build(:lighthouse526_document_upload, document_type:)).to be_valid
end
end
context 'with a document type that is not Veteran Upload' do
it 'is valid without a form_attachment_id' do
expect(build(:lighthouse526_document_upload, document_type: 'BDD Instructions', form_attachment_id: nil))
.to be_valid
end
end
end
describe 'with invalid attributes' do
it 'is invalid without a form526_submission_id' do
expect(build(:lighthouse526_document_upload, form526_submission_id: nil)).not_to be_valid
end
it 'is invalid without a lighthouse_document_request_id' do
expect(build(:lighthouse526_document_upload, lighthouse_document_request_id: nil)).not_to be_valid
end
it 'is invalid without a document_type' do
expect(build(:lighthouse526_document_upload, document_type: nil)).not_to be_valid
end
it 'is invalid without a valid document_type' do
expect(build(:lighthouse526_document_upload, document_type: 'Receipt')).not_to be_valid
end
context 'with a document_type of Veteran Upload' do
it 'is invalid without a form_attachment_id' do
expect(build(:lighthouse526_document_upload, document_type: 'Veteran Upload', form_attachment_id: nil))
.not_to be_valid
end
end
end
describe 'state transtions' do
# Both completed and failed uploads have an end time in Lighthouse
let(:finished_lighthouse526_document_upload) do
create(:lighthouse526_document_upload, lighthouse_processing_ended_at: DateTime.now)
end
it 'transitions to a completed state' do
expect(finished_lighthouse526_document_upload).to transition_from(:pending).to(:completed).on_event(:complete!)
end
it 'transitions to a failed state' do
expect(finished_lighthouse526_document_upload).to transition_from(:pending).to(:failed).on_event(:fail!)
end
describe 'transition guards' do
context 'when transitioning to a completed state' do
it 'transitions if lighthouse_processing_ended_at is saved' do
upload = create(:lighthouse526_document_upload, lighthouse_processing_ended_at: DateTime.now)
expect { upload.complete! }.not_to raise_error
end
it 'does not transition if no lighthouse_processing_ended_at is saved' do
upload = create(:lighthouse526_document_upload, lighthouse_processing_ended_at: nil)
expect { upload.complete! }.to raise_error(AASM::InvalidTransition)
end
end
context 'when transitioning to a failed state' do
it 'transitions if lighthouse_processing_ended_at is saved' do
upload = create(:lighthouse526_document_upload, lighthouse_processing_ended_at: DateTime.now)
expect { upload.fail! }.not_to raise_error
end
it 'does not transition if no lighthouse_processing_ended_at is saved' do
upload = create(:lighthouse526_document_upload, lighthouse_processing_ended_at: nil)
expect { upload.fail! }.to raise_error(AASM::InvalidTransition)
end
it 'transitions if error_message is saved' do
upload = create(
:lighthouse526_document_upload,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
expect { upload.fail! }.not_to raise_error
end
it 'does not transition if no error_message is saved' do
upload = create(:lighthouse526_document_upload, error_message: nil)
expect { upload.fail! }.to raise_error(AASM::InvalidTransition)
end
context 'when disability_compensation_email_veteran_on_polled_lighthouse_doc_failure flipper is enabled' do
before do
Flipper.enable(:disability_compensation_email_veteran_on_polled_lighthouse_doc_failure)
end
context 'when the upload was a piece of veteran-supplied evidence' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::VETERAN_UPLOAD_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form526DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail).to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
context 'when the upload was a Form 0781' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::FORM_0781_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form0781DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail).to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
context 'when the upload was a Form 0781a' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::FORM_0781A_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form0781DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail).to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
end
context 'when disability_compensation_email_veteran_on_polled_lighthouse_doc_failure flipper is disabled' do
before do
Flipper.disable(:disability_compensation_email_veteran_on_polled_lighthouse_doc_failure)
end
context 'when the upload was a piece of veteran-supplied evidence' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::VETERAN_UPLOAD_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form526DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail)
.not_to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
context 'when the upload was a Form 0781' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::FORM_0781_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form0781DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail)
.not_to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
context 'when the upload was a Form 0781a' do
let(:lighthouse526_document_upload) do
create(
:lighthouse526_document_upload,
document_type: Lighthouse526DocumentUpload::FORM_0781A_DOCUMENT_TYPE,
lighthouse_processing_ended_at: DateTime.now,
error_message: { status: 'Something broke' }.to_json
)
end
it 'enqueues a Form0781DocumentUploadFailureEmail' do
expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail)
.not_to receive(:perform_async)
lighthouse526_document_upload.fail!
end
end
end
end
end
end
describe '#form0781_types?' do
it 'returns true for Form 0781 and Form 0781a document types' do
['Form 0781', 'Form 0781a'].each do |document_type|
upload = build(:lighthouse526_document_upload, document_type:)
expect(upload.form0781_types?).to be(true)
end
end
it 'returns false for other document types' do
['BDD Instructions', 'Veteran Upload'].each do |document_type|
upload = build(:lighthouse526_document_upload, document_type:)
expect(upload.form0781_types?).to be(false)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/onsite_notification_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe OnsiteNotification, type: :model do
let(:onsite_notification) { described_class.new }
describe 'validations' do
it 'validates presence of template_id' do
expect_attr_invalid(onsite_notification, :template_id, "can't be blank")
onsite_notification.template_id = 'f9947b27-df3b-4b09-875c-7f76594d766d'
expect_attr_valid(onsite_notification, :template_id)
end
it 'validates presence of va_profile_id' do
expect_attr_invalid(onsite_notification, :va_profile_id, "can't be blank")
onsite_notification.va_profile_id = '123'
expect_attr_valid(onsite_notification, :va_profile_id)
end
it 'validates inclusion of template_id' do
onsite_notification.template_id = '123'
expect_attr_invalid(onsite_notification, :template_id, 'is not included in the list')
onsite_notification.template_id = 'f9947b27-df3b-4b09-875c-7f76594d766d'
expect_attr_valid(onsite_notification, :template_id)
onsite_notification.template_id = '7efc2b8b-e59a-4571-a2ff-0fd70253e973'
expect_attr_valid(onsite_notification, :template_id)
end
end
describe '.for_user' do
let(:user) { create(:user, :loa3) }
before do
@n1 = create(:onsite_notification, va_profile_id: user.vet360_id)
@n2 = create(:onsite_notification, va_profile_id: user.vet360_id)
@n3 = create(:onsite_notification, va_profile_id: user.vet360_id)
@n4 = create(:onsite_notification, dismissed: true, va_profile_id: user.vet360_id)
end
it 'returns non-dismissed onsite_notifications for the user' do
notifications = described_class.for_user(user)
expect(notifications.count).to eq(3)
notifications.each do |notification|
expect(notification.dismissed).to be(false)
end
end
it 'returns all onsite_notifications for the user, including dismissed ones' do
notifications = described_class.for_user(user, include_dismissed: true)
expect(notifications.count).to eq(4)
end
it 'returns onsite_notifications for the user in descending order' do
notifications = described_class.for_user(user)
notifications.zip([@n3, @n2, @n1]).each do |actual, expected|
expect(actual.created_at).to eq(expected.created_at)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/gids_redis_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe GIDSRedis do
subject { GIDSRedis.new }
let(:scrubbed_params) { {} }
let(:body) { {} }
let(:gids_response) do
GI::GIDSResponse.new(status: 200, body:)
end
context 'when `GIDSRedis` responds to method' do
context 'and the method belongs to `GI::Client`' do
it 'delegates to `GI::Client`' do
allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0).and_return(gids_response)
expect(subject.get_institution_details_v0(scrubbed_params)).to eq(gids_response.body)
end
end
context 'and the method belongs to `GI::SearchClient`' do
it 'delegates to `GI::SearchClient`' do
allow_any_instance_of(GI::SearchClient).to receive(:get_institution_search_results_v0).and_return(gids_response)
expect(subject.get_institution_search_results_v0(scrubbed_params)).to eq(gids_response.body)
end
end
context 'and the method belongs to `GI::LCPE::Client`' do
it 'delegates to `GI::LCPE::Client`' do
allow_any_instance_of(GI::LCPE::Client).to(
receive(:get_licenses_and_certs_v1).and_return(gids_response)
)
expect(subject.get_licenses_and_certs_v1(scrubbed_params)).to eq(gids_response.body)
end
end
end
context 'when `GIDSRedis` does not respond to method' do
it 'calls `super`' do
expect { subject.not_a_real_method }.to raise_error(NoMethodError)
end
end
describe 'cached attributes' do
context 'when the cache is empty' do
it 'caches and return the response', :aggregate_failures do
allow_any_instance_of(GI::Client).to receive(:get_calculator_constants_v0).and_return(gids_response)
expect(subject.redis_namespace).to receive(:set).once
expect(subject.get_calculator_constants_v0(scrubbed_params)).to be_a(Hash)
end
end
context 'when there is cached data' do
it 'returns the cached data', :aggregate_failures do
subject.cache(
:get_calculator_constants_v0.to_s + scrubbed_params.to_s,
gids_response
)
expect_any_instance_of(GI::Client).not_to receive(:get_calculator_constants_v0).with(scrubbed_params)
expect(subject.get_calculator_constants_v0(scrubbed_params)).to be_a(Hash)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_action_event_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserActionEvent, type: :model do
describe 'validations' do
subject { create(:user_action_event) }
it { is_expected.to validate_presence_of(:details) }
it { is_expected.to validate_presence_of(:identifier) }
it { is_expected.to validate_uniqueness_of(:identifier) }
it { is_expected.to validate_presence_of(:event_type) }
it { is_expected.to have_many(:user_actions).dependent(:restrict_with_exception) }
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/supporting_evidence_attachment_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SupportingEvidenceAttachment, type: :model do
describe '#obscured_filename' do
context 'for a filename longer than five characters' do
context 'for a filename containing letters' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'MySecretFile.pdf' }.to_json
)
end
it 'obscures all but the first 3 and last 2 characters of the filename' do
expect(attachment.obscured_filename).to eq('MySXXXXXXXle.pdf')
end
end
context 'for a filename containing numbers' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'MySecretFile123.pdf' }.to_json
)
end
it 'obscures the filename' do
expect(attachment.obscured_filename).to eq('MySXXXXXXXXXX23.pdf')
end
end
context 'for a filename containing underscores' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'MySecretFile_123.pdf' }.to_json
)
end
it 'does not obscure the underscores' do
expect(attachment.obscured_filename).to eq('MySXXXXXXXXX_X23.pdf')
end
end
context 'for a filename containing dashes' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'MySecretFile-123.pdf' }.to_json
)
end
it 'does not obscure the dashes' do
expect(attachment.obscured_filename).to eq('MySXXXXXXXXX-X23.pdf')
end
end
# Ensure Regexp still handles the file extension properly
context 'for a filename containing a dot' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'MySecret.File123.pdf' }.to_json
)
end
it 'obsucres the filename properly' do
expect(attachment.obscured_filename).to eq('MySXXXXX.XXXXX23.pdf')
end
end
context 'for a filename containing whitespace' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'My Secret File.pdf' }.to_json
)
end
it 'preserves the whitespace' do
expect(attachment.obscured_filename).to eq('My XXXXXX XXle.pdf')
end
end
end
context 'for a filename with five characters or less' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: { filename: 'File.pdf' }.to_json
)
end
it 'does not obscure the filename' do
expect(attachment.obscured_filename).to eq('File.pdf')
end
end
# NOTE: Filetypes that need to be converted in EVSSClaimDocumentUploaderBase
# have 'converted_' prepended to the file name and saved as converted_filename in the file_data
# Ensure the obscured_filename method is masking the original filename
# This is the name of the file the veteran originally uploaded so it will be recognizable to them
context 'for a file with a converted file name' do
let(:attachment) do
build(
:supporting_evidence_attachment,
file_data: {
filename: 'File123.pdf',
converted_filename: 'converted_File123.pdf'
}.to_json
)
end
it 'obscures the original filename' do
expect(attachment.obscured_filename).to eq('FilXX23.pdf')
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/id_card_announcement_subscription_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe IdCardAnnouncementSubscription, type: :model do
describe 'when validating' do
it 'requires a valid email address' do
subscription = described_class.new(email: 'invalid')
expect_attr_invalid(subscription, :email, 'is invalid')
end
it 'requires less than 255 characters in an email address' do
email = "#{'x' * 255}@example.com"
subscription = described_class.new(email:)
expect_attr_invalid(subscription, :email, 'is too long (maximum is 255 characters)')
end
it 'requires a unique email address' do
email = 'nonunique@example.com'
described_class.create(email:)
subscription = described_class.new(email:)
expect_attr_invalid(subscription, :email, 'has already been taken')
end
end
describe 'va scope' do
let!(:va_subscription) { described_class.create(email: 'test@va.gov') }
let!(:subscription) { described_class.create(email: 'test@example.com') }
it 'includes records with a @va.gov domain' do
expect(described_class.va).to include(va_subscription)
end
it 'does not include records without a @va.gov domain' do
expect(described_class.va).not_to include(subscription)
end
end
describe 'non-va scope' do
let!(:va_subscription) { described_class.create(email: 'test@va.gov') }
let!(:subscription) { described_class.create(email: 'test@example.com') }
it 'includes records without a @va.gov domain' do
expect(described_class.non_va).to include(subscription)
end
it 'does not include records with a @va.gov domain' do
expect(described_class.non_va).not_to include(va_subscription)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_session_form_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/saml/response_builder'
RSpec.describe UserSessionForm, type: :model do
include SAML::ResponseBuilder
let(:loa3_user) do
build(:user, :loa3, uuid: saml_attributes[:uuid],
idme_uuid: saml_attributes[:uuid])
end
let(:authn_context) { 'http://idmanagement.gov/ns/assurance/loa/3/vets' }
let(:saml_response) do
build_saml_response(
authn_context:,
level_of_assurance: '3',
attributes: saml_attributes,
existing_attributes: nil,
issuer: 'https://int.eauth.va.gov/FIM/sps/saml20fedCSP/saml20'
)
end
context 'with ID.me UUID in SAML' do
let(:saml_attributes) do
build(:ssoe_idme_mhv_premium, va_eauth_gcIds: va_eauth_gc_ids)
end
let(:va_eauth_gc_ids) do
['1012853550V207686^NI^200M^USVHA^P|' \
'552151510^PI^989^USVHA^A|' \
'943571^PI^979^USVHA^A|' \
'12345748^PI^200MH^USVHA^A|' \
'1012853550^PN^200PROV^USDVA^A|' \
'7219295^PI^983^USVHA^A|' \
'552161765^PI^984^USVHA^A|' \
'2107307560^NI^200DOD^USDOD^A|' \
'7b9b5861203244f0b99b02b771159044^PN^200VIDM^USDVA^A|' \
'0e1bb5723d7c4f0686f46ca4505642ad^PN^200VIDM^USDVA^A|' \
'12345748^PI^200MHS^USVHA^A']
end
it 'instantiates cleanly' do
UserSessionForm.new(saml_response)
end
it 'instantiates with a Session SSOe transactionid' do
form = UserSessionForm.new(saml_response)
expect(form.session[:ssoe_transactionid])
.to eq(saml_attributes['va_eauth_transactionid'])
end
it 'instantiates with an expected id.me UUID' do
form = UserSessionForm.new(saml_response)
expect(form.user_identity.idme_uuid)
.to eq(saml_attributes['va_eauth_uid'])
end
context 'and ID.me UUID not in SAML GCids' do
let(:va_eauth_gc_ids) do
['1012853550V207686^NI^200M^USVHA^P|' \
'552151510^PI^989^USVHA^A|' \
'943571^PI^979^USVHA^A|' \
'12345748^PI^200MH^USVHA^A|' \
'1012853550^PN^200PROV^USDVA^A|' \
'7219295^PI^983^USVHA^A|' \
'552161765^PI^984^USVHA^A|' \
'2107307560^NI^200DOD^USDOD^A|' \
'12345748^PI^200MHS^USVHA^A']
end
let(:add_person_response) do
MPI::Responses::AddPersonResponse.new(status:, parsed_codes:)
end
let(:status) { 'OK' }
let(:parsed_codes) { { icn: saml_attributes[:va_eauth_icn] } }
before do
allow_any_instance_of(MPI::Service).to receive(:add_person_implicit_search).and_return(add_person_response)
end
it 'adds the ID.me UUID to the existing mpi record' do
expect_any_instance_of(MPI::Service).to receive(:add_person_implicit_search)
UserSessionForm.new(saml_response)
end
end
end
context 'with ID.me UUID not present in SAML' do
context 'and Login.gov UUID is not present in SAML' do
let(:saml_attributes) do
build(:ssoe_inbound_mhv_premium, va_eauth_gcIds: [''])
end
let(:icn) { saml_attributes[:va_eauth_icn] }
let(:user_account) { user_verification.user_account }
let!(:user_verification) { create(:idme_user_verification) }
context 'and there are no existing user account mappings for the user' do
let(:user_account) { nil }
let(:user_verification) { nil }
let(:expected_error) { SAML::UserAttributeError }
it 'raises a saml user attribute error' do
expect { UserSessionForm.new(saml_response) }.to raise_error(expected_error)
end
end
context 'when credential identifier can be found on existing account' do
let(:user_account) { create(:user_account, icn: saml_attributes[:va_eauth_icn]) }
let!(:user_verification) { create(:user_verification, user_account:) }
let(:idme_uuid) { user_verification.idme_uuid }
let(:add_person_response) do
MPI::Responses::AddPersonResponse.new(status:, parsed_codes:)
end
let(:status) { 'OK' }
let(:parsed_codes) { { icn: saml_attributes[:va_eauth_icn] } }
before do
allow_any_instance_of(MPI::Service).to receive(:add_person_implicit_search).and_return(add_person_response)
end
it 'uses the user account uuid as the user key' do
subject = UserSessionForm.new(saml_response)
subject.persist
expect(User.find(user_account.id)).to be_truthy
expect(UserIdentity.find(user_account.id)).to be_truthy
end
it 'adds the identifier to an existing mpi record' do
expect_any_instance_of(MPI::Service).to receive(:add_person_implicit_search)
UserSessionForm.new(saml_response)
end
context 'when failure occurs during adding identifier to existing mpi record' do
let(:status) { 'some-not-successful-status' }
it 'logs a message to Rails logger' do
expect(Rails.logger).to receive(:warn).with(
'[UserSessionForm] Failed Add CSP ID to MPI',
idme_uuid:
)
UserSessionForm.new(saml_response)
end
end
end
end
context 'and Login.gov UUID is present in SAML' do
let(:authn_context) { 'http://idmanagement.gov/ns/assurance/ial/2/mfa' }
let(:saml_attributes) do
build(:ssoe_logingov_ial2)
end
it 'instantiates cleanly' do
UserSessionForm.new(saml_response)
end
it 'instantiates with a Session SSOe transactionid' do
form = UserSessionForm.new(saml_response)
expect(form.session[:ssoe_transactionid])
.to eq(saml_attributes['va_eauth_transactionid'])
end
it 'instantiates with an expected login.gov UUID' do
form = UserSessionForm.new(saml_response)
expect(form.user_identity.logingov_uuid)
.to eq(saml_attributes['va_eauth_uid'])
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/appeal_submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe AppealSubmission, type: :model do
describe '#get_mpi_profile' do
subject { appeal_submission.get_mpi_profile }
let(:user) { create(:user, :loa3) }
let(:user_account) { user.user_account }
let(:mpi_profile) { build(:mpi_profile, icn: user_account.icn) }
let(:find_profile_response) { create(:find_profile_response, profile: mpi_profile) }
let(:appeal_submission) { create(:appeal_submission, user_account:, user_uuid: user.uuid) }
let(:identifier) { user_account.icn }
let(:identifier_type) { MPI::Constants::ICN }
before do
allow(User).to receive(:find).with(user.uuid).and_return(user)
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).with(identifier:, identifier_type:)
.and_return(find_profile_response)
end
context 'when a UserAccount with an ICN is present' do
it 'calls the MPI service with the appropriate identifier and identifier type' do
expect_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).with(identifier:, identifier_type:)
subject
end
it 'returns the MPI profile' do
expect(subject).to eq(mpi_profile)
end
end
context 'when a UserAccount with an ICN is not present' do
let(:find_profile_response) { create(:find_profile_not_found_response) }
let(:identifier) { nil }
let(:expected_error) { 'Failed to fetch MPI profile' }
before { user_account.icn = nil }
it 'raises an error' do
expect { subject }.to raise_error(StandardError, expected_error)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/health_care_application_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'kafka/sidekiq/event_bus_submission_job'
RSpec.describe HealthCareApplication, type: :model do
let(:health_care_application) { create(:health_care_application) }
let(:health_care_application_short_form) do
short_form = JSON.parse(health_care_application.form)
short_form.delete('lastServiceBranch')
short_form['vaCompensationType'] = 'highDisability'
short_form
end
let(:inelig_character_of_discharge) { HCA::EnrollmentEligibility::Constants::INELIG_CHARACTER_OF_DISCHARGE }
let(:statsd_key_prefix) { HCA::Service::STATSD_KEY_PREFIX }
let(:zsf_tags) { described_class::DD_ZSF_TAGS }
let(:form_id) { described_class::FORM_ID }
before do
allow(Flipper).to receive(:enabled?).with(:hca_ez_kafka_submission_enabled).and_return(true)
end
describe 'LOCKBOX' do
it 'can encrypt strings over 4kb' do
str = 'f' * 6000
lockbox = described_class::LOCKBOX
expect(lockbox.decrypt(lockbox.encrypt(str))).to eq(str)
end
end
describe 'schema' do
it 'is deep frozen' do
expect do
VetsJsonSchema::SCHEMAS['10-10EZ']['title'] = 'foo'
end.to raise_error(FrozenError)
expect(VetsJsonSchema::SCHEMAS['10-10EZ']['title']).to eq('APPLICATION FOR HEALTH BENEFITS (10-10EZ)')
end
end
describe '#prefill_fields' do
let(:health_care_application) { build(:health_care_application) }
context 'with missing fields' do
before do
health_care_application.parsed_form.delete('veteranFullName')
health_care_application.parsed_form.delete('veteranDateOfBirth')
health_care_application.parsed_form.delete('veteranSocialSecurityNumber')
end
context 'without a user' do
it 'does nothing' do
expect(health_care_application.send(:prefill_fields)).to be_nil
expect(health_care_application.valid?).to be(false)
end
end
context 'with a user' do
before do
health_care_application.user = user
end
context 'with a loa1 user' do
let(:user) { create(:user) }
it 'does nothing' do
expect(health_care_application.send(:prefill_fields)).to be_nil
expect(health_care_application.valid?).to be(false)
end
end
context 'with a loa3 user' do
let(:user) { create(:user, :loa3) }
context 'with a nil birth_date' do
before do
health_care_application.parsed_form['veteranDateOfBirth'] = '1923-01-02'
expect(user).to receive(:birth_date).and_return(nil)
end
it 'doesnt set a field if the user data is null' do
health_care_application.send(:prefill_fields)
parsed_form = health_care_application.parsed_form
expect(parsed_form['veteranDateOfBirth']).to eq('1923-01-02')
expect(parsed_form['veteranSocialSecurityNumber']).to eq(user.ssn_normalized)
end
end
it 'sets uneditable fields using user data' do
expect(health_care_application.valid?).to be(false)
health_care_application.send(:prefill_fields)
expect(health_care_application.valid?).to be(true)
parsed_form = health_care_application.parsed_form
expect(parsed_form['veteranFullName']).to eq(user.full_name_normalized.compact.stringify_keys)
expect(parsed_form['veteranDateOfBirth']).to eq(user.birth_date)
expect(parsed_form['veteranSocialSecurityNumber']).to eq(user.ssn_normalized)
end
end
end
end
end
describe '.enrollment_status' do
it 'returns parsed enrollment status' do
expect_any_instance_of(HCA::EnrollmentEligibility::Service).to receive(:lookup_user).with(
'123'
).and_return(
enrollment_status: 'Not Eligible; Ineligible Date',
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
ineligibility_reason: 'OTH',
effective_date: '2018-01-24T00:00:00.000-09:00'
)
expect(described_class.enrollment_status('123', true)).to eq(
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
parsed_status: inelig_character_of_discharge,
effective_date: '2018-01-24T00:00:00.000-09:00'
)
end
end
describe '.parsed_ee_data' do
let(:ee_data) do
{
enrollment_status: 'Not Eligible; Ineligible Date',
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
ineligibility_reason: 'OTH',
effective_date: '2018-01-24T00:00:00.000-09:00',
primary_eligibility: 'SC LESS THAN 50%'
}
end
context 'with a loa3 user' do
it 'returns the full parsed ee data' do
expect(described_class.parsed_ee_data(ee_data, true)).to eq(
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
parsed_status: inelig_character_of_discharge,
effective_date: '2018-01-24T00:00:00.000-09:00',
primary_eligibility: 'SC LESS THAN 50%'
)
end
context 'with an active duty service member' do
let(:ee_data) do
{
enrollment_status: 'not applicable',
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
ineligibility_reason: 'OTH',
primary_eligibility: 'TRICARE',
veteran: 'false',
effective_date: '2018-01-24T00:00:00.000-09:00'
}
end
it 'returns the right parsed_status' do
expect(described_class.parsed_ee_data(ee_data, true)[:parsed_status]).to eq(
HCA::EnrollmentEligibility::Constants::ACTIVEDUTY
)
end
end
context 'when the user isnt active duty' do
let(:ee_data) do
{
enrollment_status: 'not applicable',
application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
ineligibility_reason: 'OTH',
primary_eligibility: 'SC LESS THAN 50%',
veteran: 'true',
effective_date: '2018-01-24T00:00:00.000-09:00'
}
end
it 'returns the right parsed_status' do
expect(described_class.parsed_ee_data(ee_data, true)[:parsed_status]).to eq(
HCA::EnrollmentEligibility::Constants::NON_MILITARY
)
end
end
end
context 'with a loa1 user' do
context 'when enrollment_status is present' do
it 'returns partial ee data' do
expect(described_class.parsed_ee_data(ee_data, false)).to eq(
parsed_status: HCA::EnrollmentEligibility::Constants::LOGIN_REQUIRED
)
end
end
context 'when enrollment_status is not set' do
it 'returns none of the above ee data' do
expect(described_class.parsed_ee_data({}, false)).to eq(
parsed_status: HCA::EnrollmentEligibility::Constants::NONE_OF_THE_ABOVE
)
end
end
end
end
describe '.user_icn' do
let(:form) { health_care_application.parsed_form }
context 'when the user is not found' do
it 'returns nil' do
expect_any_instance_of(MPI::Service).to receive(
:find_profile_by_attributes
).and_return(
create(:find_profile_not_found_response)
)
expect(described_class.user_icn(described_class.user_attributes(form))).to be_nil
end
end
context 'when the user is found' do
it 'returns the icn' do
expect_any_instance_of(MPI::Service).to receive(
:find_profile_by_attributes
).and_return(
create(:find_profile_response, profile: OpenStruct.new(icn: '123'))
)
expect(described_class.user_icn(described_class.user_attributes(form))).to eq('123')
end
end
end
describe '.user_attributes' do
subject(:user_attributes) do
described_class.user_attributes(form)
end
let(:form) { health_care_application.parsed_form }
it 'creates a mvi compatible hash of attributes' do
expect(
user_attributes.to_h
).to eq(
first_name: 'FirstName',
middle_name: 'MiddleName',
last_name: 'ZZTEST',
birth_date: '1923-01-02',
ssn: '111111234'
)
end
it 'creates user_attributes with uuid' do
allow(SecureRandom).to receive(:uuid).and_return('my-uuid')
expect(
user_attributes.uuid
).to eq('my-uuid')
end
context 'with a nil form' do
let(:form) { nil }
it 'raises a validation error' do
expect do
user_attributes
end.to raise_error(Common::Exceptions::ValidationErrors)
end
end
end
describe '#send_event_bus_event' do
let(:health_care_application) { create(:health_care_application) }
let(:user_attributes) do
an_object_having_attributes(
first_name: 'FirstName',
middle_name: 'MiddleName',
last_name: 'ZZTEST',
birth_date: '1923-01-02',
ssn: '111111234'
)
end
context 'with a user' do
let(:user) { create(:user) }
before do
health_care_application.user = user
end
it 'calls Kafka.submit event with the right arguments' do
expect(Kafka).to receive(:submit_event).with(
icn: user.icn,
current_id: health_care_application.id,
submission_name: 'F1010EZ', state: 'received',
next_id: nil
)
health_care_application.send_event_bus_event('received')
end
context 'without an icn' do
before do
health_care_application.user = build(:user, icn: nil)
end
it 'falls back on looking up the user icn' do
allow(described_class).to receive(:user_icn).with(user_attributes).and_return('123')
expect(Kafka).to receive(:submit_event).with(
icn: '123', current_id: health_care_application.id,
submission_name: 'F1010EZ', state: 'sent',
next_id: '456'
)
health_care_application.send_event_bus_event('sent', '456')
end
end
end
context 'without a user' do
it 'returns the right payload' do
allow(described_class).to receive(:user_icn).with(user_attributes).and_return('123')
expect(Kafka).to receive(:submit_event).with(
icn: '123', current_id: health_care_application.id,
submission_name: 'F1010EZ', state: 'received', next_id: nil
)
health_care_application.send_event_bus_event('received')
end
it 'returns the right payload with a next id' do
allow(described_class).to receive(:user_icn)
.with(user_attributes).and_return('123')
expect(Kafka).to receive(:submit_event).with(
icn: '123', current_id: health_care_application.id,
submission_name: 'F1010EZ', state: 'sent',
next_id: '456'
)
health_care_application.send_event_bus_event('sent', '456')
end
context 'and invalid user attributes' do
let(:invalid_user_attributes) { double(errors: ['error']) }
before do
allow(described_class).to receive(:user_attributes) \
.and_raise(
Common::Exceptions::ValidationErrors.new(invalid_user_attributes)
)
end
it 'returns a payload with no ICN' do
expect(Kafka).to receive(:submit_event).with(
icn: nil, current_id: health_care_application.id,
submission_name: 'F1010EZ', state: 'received', next_id: nil
)
health_care_application.send_event_bus_event('received')
end
end
end
context 'with the hca_ez_kafka_submission_enabled feature flag off' do
before do
allow(Flipper).to receive(:enabled?).with(:hca_ez_kafka_submission_enabled).and_return(false)
end
it 'does not call Kafka.submit_event' do
expect(Kafka).not_to receive(:submit_event)
health_care_application.send_event_bus_event('received')
end
end
end
describe 'validations' do
context 'long form validations' do
let(:health_care_application) { build(:health_care_application) }
before do
%w[
maritalStatus
isEnrolledMedicarePartA
lastServiceBranch
lastEntryDate
lastDischargeDate
].each do |attr|
health_care_application.parsed_form.delete(attr)
end
end
context 'with a va compensation type of highDisability' do
before do
health_care_application.parsed_form['vaCompensationType'] = 'highDisability'
end
it 'doesnt require the long form fields' do
expect(health_care_application.valid?).to be(true)
end
end
context 'with a va compensation type of none' do
before do
health_care_application.parsed_form['vaCompensationType'] = 'none'
end
it 'allows false for boolean fields' do
health_care_application.parsed_form['isEnrolledMedicarePartA'] = false
health_care_application.valid?
expect(health_care_application.errors[:form]).to eq(
[
"maritalStatus can't be null",
"lastServiceBranch can't be null",
"lastEntryDate can't be null",
"lastDischargeDate can't be null"
]
)
end
it 'requires the long form fields' do
health_care_application.valid?
expect(health_care_application.errors[:form]).to eq(
[
"maritalStatus can't be null",
"isEnrolledMedicarePartA can't be null",
"lastServiceBranch can't be null",
"lastEntryDate can't be null",
"lastDischargeDate can't be null"
]
)
end
end
end
it 'validates presence of state' do
health_care_application = described_class.new(state: nil)
expect_attr_invalid(health_care_application, :state, "can't be blank")
end
it 'validates inclusion of state' do
health_care_application = described_class.new
%w[success error failed pending].each do |state|
health_care_application.state = state
expect_attr_valid(health_care_application, :state)
end
health_care_application.state = 'foo'
expect_attr_invalid(health_care_application, :state, 'is not included in the list')
end
it 'validates presence of form_submission_id and timestamp if success' do
health_care_application = described_class.new
%w[form_submission_id_string timestamp].each do |attr|
health_care_application.state = 'success'
expect_attr_invalid(health_care_application, attr, "can't be blank")
health_care_application.state = 'pending'
expect_attr_valid(health_care_application, attr)
end
end
context 'schema validation error' do
let(:health_care_application) { build(:health_care_application) }
let(:schema) { 'schema_content' }
let(:schemer_errors) do
[{
data_pointer: 'data_pointer',
error: 'some error',
details: { detail: 'thing' },
schema: { detail: 'schema' },
root_schema: { detail: 'root_schema' },
data: { key: 'this could be pii' }
}]
end
before do
allow(VetsJsonSchema::SCHEMAS).to receive(:[]).and_return(schema)
allow(JSONSchemer).to receive(:schema).and_return(double(:fake_schema,
validate: schemer_errors))
end
it 'sets errors' do
health_care_application.valid?
expect(health_care_application.errors[:form]).to eq ['some error']
end
end
end
describe '#process!' do
let(:health_care_application) { build(:health_care_application) }
before do
allow_any_instance_of(MPI::Service).to receive(
:find_profile_by_attributes
).and_return(
create(:find_profile_response, profile: OpenStruct.new(icn: '123'))
)
end
it 'calls prefill fields' do
expect(health_care_application).to receive(:prefill_fields)
health_care_application.process!
end
describe '#parsed_form overrides' do
before do
health_care_application.parsed_form.tap do |form|
form['veteranAddress']['country'] = 'MEX'
form['veteranAddress']['state'] = 'aguascalientes'
end
end
it 'sets the proper abbreviation for states in Mexico' do
expect(health_care_application).to receive(:prefill_fields)
health_care_application.process!
form = health_care_application.parsed_form
expect(form['veteranAddress']['state']).to eq('AGS.')
end
end
context 'with an invalid record' do
it 'adds user loa to extra context' do
expect(Sentry).to receive(:set_extras).with(user_loa: { current: 1, highest: 3 })
expect do
described_class.new(form: {}.to_json, user: build(:user)).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
end
it 'creates a PersonalInformationLog' do
expect do
described_class.new(form: { test: 'test' }.to_json).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
personal_information_log = PersonalInformationLog.last
expect(personal_information_log.data).to eq('test' => 'test')
expect(personal_information_log.error_class).to eq('HealthCareApplication ValidationError')
end
it 'raises a validation error' do
expect do
described_class.new(form: {}.to_json).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
end
it 'triggers short form statsd' do
expect do
expect do
described_class.new(form: { mothersMaidenName: 'm' }.to_json).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
end.to trigger_statsd_increment("#{statsd_key_prefix}.validation_error_short_form")
end
it 'triggers statsd' do
expect do
expect do
described_class.new(form: {}.to_json).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
end.to trigger_statsd_increment("#{statsd_key_prefix}.validation_error")
end
it 'does not send "received" event' do
allow(Kafka).to receive(:submit_event)
expect(Kafka).not_to have_received(:submit_event)
expect do
described_class.new(form: {}.to_json).process!
end.to raise_error(Common::Exceptions::ValidationErrors)
end
end
def self.expect_job_submission(job)
it "submits using the #{job}" do
user = build(:user, edipi: 'my_edipi', icn: 'my_icn')
allow_any_instance_of(HealthCareApplication).to receive(:id).and_return(1)
allow_any_instance_of(HealthCareApplication).to receive(:user).and_return(user)
expect_any_instance_of(HealthCareApplication).to receive(:save!)
expect(job).to receive(:perform_async) do |
user_identifier, encrypted_form, health_care_application_id, google_analytics_client_id
|
expect(user_identifier).to eq({ 'icn' => user.icn, 'edipi' => user.edipi })
expect(HCA::SubmissionJob.decrypt_form(encrypted_form)).to eq(health_care_application.parsed_form)
expect(health_care_application_id).to eq(1)
expect(google_analytics_client_id).to be_nil
end
expect(health_care_application.process!).to eq(health_care_application)
end
end
context 'with an email' do
expect_job_submission(HCA::SubmissionJob)
it 'sends the "received" event' do
expect(Kafka).to receive(:submit_event).with(
hash_including(state: 'received')
)
health_care_application.process!
end
end
context 'with no email' do
let(:service_instance) { instance_double(HCA::Service) }
let(:parsed_form) { health_care_application.send(:parsed_form) }
let(:success_result) { { success: true, formSubmissionId: '123', timestamp: Time.now.getlocal.to_s } }
before do
new_form = JSON.parse(health_care_application.form)
new_form.delete('email')
health_care_application.form = new_form.to_json
health_care_application.instance_variable_set(:@parsed_form, nil)
allow(HCA::Service).to receive(:new).and_return(service_instance)
end
context 'successful submission' do
before do
allow(service_instance).to receive(:submit_form)
.with(parsed_form)
.and_return(success_result)
end
it 'successfully submits synchronously' do
expect(health_care_application.process!).to eq(success_result)
end
it 'saves the HCA record' do
health_care_application.process!
health_care_application.reload
expect(health_care_application.id).not_to be_nil
expect(health_care_application.state).to eq('success')
end
it 'sends the "received", and "sent" event' do
expect(Kafka).to receive(:submit_event).with(
hash_including(
state: 'received',
current_id: satisfy { |v| !v.nil? }
)
)
expect(Kafka).to receive(:submit_event).with(
hash_including(
state: 'sent',
next_id: '123',
current_id: satisfy { |v| !v.nil? }
)
)
health_care_application.process!
end
end
context 'exception is raised in process!' do
let(:client_error) { Common::Client::Errors::ClientError.new('error message flerp') }
before do
allow(StatsD).to receive(:increment)
allow(service_instance).to receive(:submit_form)
.and_raise(client_error)
end
it 'logs exception and raises BackendServiceException' do
expect(Rails.logger).to receive(:error).with(
'[10-10EZ] - Error synchronously submitting form',
{
exception: client_error, user_loa: nil
}
)
expect(Rails.logger).to receive(:info).with(
'[10-10EZ] - HCA total failure',
{
first_initial: 'F',
middle_initial: 'M',
last_initial: 'Z'
}
)
expect do
health_care_application.process!
end.to raise_error(Common::Exceptions::BackendServiceException)
end
it 'increments statsd' do
expect(StatsD).to receive(:increment).with("#{statsd_key_prefix}.sync_submission_failed")
expect do
health_care_application.process!
end.to raise_error(Common::Exceptions::BackendServiceException)
end
it 'sends an error event to the Event Bus' do
expect(Kafka).to receive(:submit_event).with(hash_including(state: 'received'))
expect(Kafka).to receive(:submit_event).with(hash_including(state: 'error'))
expect do
health_care_application.process!
end.to raise_error(Common::Exceptions::BackendServiceException)
end
context 'short form' do
before do
health_care_application.form = health_care_application_short_form.to_json
health_care_application.instance_variable_set(:@parsed_form, nil)
end
it 'increments statsd and short_form statsd' do
expect(StatsD).to receive(:increment).with("#{statsd_key_prefix}.sync_submission_failed")
expect(StatsD).to receive(:increment).with("#{statsd_key_prefix}.sync_submission_failed_short_form")
expect do
health_care_application.process!
end.to raise_error(Common::Exceptions::BackendServiceException)
end
end
end
end
end
describe 'when state changes to "failed"' do
subject do
health_care_application.update!(state: 'failed')
health_care_application
end
before do
allow(VANotify::EmailJob).to receive(:perform_async)
allow_any_instance_of(MPI::Service).to receive(
:find_profile_by_attributes
).and_return(
create(:find_profile_response, profile: OpenStruct.new(icn: '123'))
)
end
describe '#send_failure_email' do
context 'has form' do
context 'with email address' do
let(:email_address) { health_care_application.parsed_form['email'] }
let(:api_key) { Settings.vanotify.services.health_apps_1010.api_key }
let(:template_id) { Settings.vanotify.services.health_apps_1010.template_id.form1010_ez_failure_email }
let(:callback_metadata) do
{
callback_metadata: {
notification_type: 'error',
form_number: form_id,
statsd_tags: zsf_tags
}
}
end
let(:template_params) do
[
email_address,
template_id,
{
'salutation' => "Dear #{health_care_application.parsed_form['veteranFullName']['first']},"
},
api_key,
callback_metadata
]
end
let(:standard_error) { StandardError.new('Test error') }
it 'sends a failure email to the email address provided on the form' do
subject
expect(VANotify::EmailJob).to have_received(:perform_async).with(*template_params)
end
it 'logs error if email job throws error' do
allow(VANotify::EmailJob).to receive(:perform_async).and_raise(standard_error)
expect(Rails.logger).to receive(:error).with(
'[10-10EZ] - Failure sending Submission Failure Email',
{ exception: standard_error }
)
expect(Rails.logger).to receive(:info).with(
'[10-10EZ] - HCA total failure',
{
first_initial: 'F',
middle_initial: 'M',
last_initial: 'Z'
}
)
expect { subject }.not_to raise_error
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment("#{statsd_key_prefix}.submission_failure_email_sent")
end
context 'without first name' do
subject do
health_care_application.parsed_form['veteranFullName'] = nil
super()
end
let(:template_params_no_name) do
[
email_address,
template_id,
{
'salutation' => ''
},
api_key,
callback_metadata
]
end
let(:standard_error) { StandardError.new('Test error') }
it 'sends a failure email without personalisations to the email address provided on the form' do
subject
expect(VANotify::EmailJob).to have_received(:perform_async).with(*template_params_no_name)
end
it 'logs error if email job throws error' do
allow(VANotify::EmailJob).to receive(:perform_async).and_raise(standard_error)
expect(Rails.logger).to receive(:error).with(
'[10-10EZ] - Failure sending Submission Failure Email',
{ exception: standard_error }
)
expect(Rails.logger).to receive(:info).with(
'[10-10EZ] - HCA total failure',
{
first_initial: 'no initial provided',
middle_initial: 'no initial provided',
last_initial: 'no initial provided'
}
)
expect { subject }.not_to raise_error
end
end
end
context 'without email address' do
subject do
health_care_application.parsed_form['email'] = nil
super()
end
it 'does not send email' do
expect(health_care_application).not_to receive(:send_failure_email)
subject
end
end
end
context 'does not have form' do
subject do
health_care_application.form = nil
super()
end
context 'with email address' do
it 'does not send email' do
expect(health_care_application).not_to receive(:send_failure_email)
subject
end
end
context 'without email address' do
subject do
health_care_application.parsed_form['email'] = nil
super()
end
it 'does not send email' do
expect(health_care_application).not_to receive(:send_failure_email)
subject
end
end
end
end
describe '#log_async_submission_failure' do
it 'triggers failed_wont_retry statsd' do
expect { subject }.to trigger_statsd_increment("#{statsd_key_prefix}.failed_wont_retry")
end
context 'short form' do
before do
health_care_application.form = health_care_application_short_form.to_json
health_care_application.instance_variable_set(:@parsed_form, nil)
end
it 'triggers statsd' do
expect { subject }.to trigger_statsd_increment("#{statsd_key_prefix}.failed_wont_retry")
.and trigger_statsd_increment("#{statsd_key_prefix}.failed_wont_retry_short_form")
end
end
context 'form is present' do
it 'logs form to PersonalInformationLog' do
subject
pii_log = PersonalInformationLog.last
expect(pii_log.error_class).to eq('HealthCareApplication FailedWontRetry')
expect(pii_log.data).to eq(health_care_application.parsed_form)
end
it 'logs message' do
expect(Rails.logger).to receive(:info).with(
'[10-10EZ] - HCA total failure',
{
first_initial: 'F',
middle_initial: 'M',
last_initial: 'Z'
}
)
subject
end
it 'sends the "error" event to the Event Bus' do
expect(Kafka).to receive(:submit_event).with(hash_including(state: 'error'))
subject
end
end
context 'hca_ez_kafka_submission_enabled feature flag off' do
before do
allow(Flipper).to receive(:enabled?).with(:hca_ez_kafka_submission_enabled).and_return(false)
end
it 'does not send the "error" event to the Event Bus' do
expect(Kafka).not_to receive(:submit_event).with(hash_including(state: 'error'))
subject
end
end
context '@parsed_form is nil' do
before do
health_care_application.instance_variable_set(:@parsed_form, nil)
end
context 'form is empty' do
before do
health_care_application.form = {}.to_json
end
it 'does not log form to PersonalInformationLog' do
subject
expect(PersonalInformationLog.count).to eq 0
end
it 'does not log message' do
expect(Rails.logger).not_to receive(:error)
subject
end
end
context 'form does not have veteranFullName' do
before do
health_care_application.form = { email: 'my_email@email.com' }.to_json
end
it 'logs form to PersonalInformationLog' do
subject
pii_log = PersonalInformationLog.last
expect(pii_log.error_class).to eq('HealthCareApplication FailedWontRetry')
expect(pii_log.data).to eq(health_care_application.parsed_form)
end
it 'logs message' do
expect(Rails.logger).to receive(:info).with(
'[10-10EZ] - HCA total failure',
{
first_initial: 'no initial provided',
middle_initial: 'no initial provided',
last_initial: 'no initial provided'
}
)
subject
end
end
end
end
end
describe '#set_result_on_success!' do
let(:result) do
{
formSubmissionId: 123,
timestamp: '2017-08-03 22:02:18 -0400'
}
end
before do
allow_any_instance_of(MPI::Service).to receive(
:find_profile_by_attributes
).and_return(
create(:find_profile_response, profile: OpenStruct.new(icn: '123'))
)
end
it 'sets the right fields and save the application' do
health_care_application = build(:health_care_application)
health_care_application.set_result_on_success!(result)
expect(health_care_application.id.present?).to be(true)
expect(health_care_application.success?).to be(true)
expect(health_care_application.form_submission_id).to eq(result[:formSubmissionId])
expect(health_care_application.timestamp).to eq(result[:timestamp])
end
it 'sends the "sent" event to the Event Bus' do
health_care_application = build(:health_care_application)
expect(Kafka).to receive(:submit_event).with(
hash_including(
state: 'sent',
next_id: result[:formSubmissionId].to_s
)
)
health_care_application.set_result_on_success!(result)
end
context 'hca_ez_kafka_submission_enabled feature flag off' do
before do
allow(Flipper).to receive(:enabled?).with(:hca_ez_kafka_submission_enabled).and_return(false)
end
it 'does not send the "sent" event to the Event Bus' do
health_care_application = build(:health_care_application)
expect(Kafka).not_to receive(:submit_event).with(
hash_including(state: 'sent')
)
health_care_application.set_result_on_success!(result)
end
end
end
describe '#parsed_form' do
subject { health_care_application.parsed_form }
let(:form) { Rails.root.join('spec', 'fixtures', 'hca', 'veteran.json').read }
context '@parsed_form is already set' do
it 'returns parsed_form' do
expect(subject).to eq JSON.parse(form)
end
context 'form is nil' do
before do
health_care_application.form = nil
end
it 'returns parsed_form' do
expect(subject).to eq JSON.parse(form)
end
end
end
context '@parsed_form is nil' do
before do
health_care_application.instance_variable_set(:@parsed_form, nil)
end
it 'returns parsed form' do
expect(subject).to eq JSON.parse(form)
end
context 'form is nil' do
before do
health_care_application.form = nil
end
it 'returns nil' do
expect(subject).to be_nil
end
end
end
end
describe '#form_id' do
it 'has form_id from FORM_ID const' do
expect(health_care_application.form_id).to eq described_class::FORM_ID
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/form526_submission_remediation_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Form526SubmissionRemediation, type: :model do
subject do
described_class.new(form526_submission:, lifecycle: [])
end
let(:form526_submission) { create(:form526_submission) }
let(:remediate_context) { 'Failed remediation' }
describe 'associations' do
it { is_expected.to belong_to(:form526_submission) }
end
describe 'validations' do
context 'remediation_type validation' do
it 'defines an enum for remediation type' do
enum_values = %i[manual ignored_as_duplicate email_notified]
expect(define_enum_for(:remediation_type).with_values(enum_values)).to be_truthy
end
end
context 'lifecycle validation' do
it 'is invalid without context on create' do
expect(subject).not_to be_valid
end
it 'is invalid without context on update' do
subject.mark_as_unsuccessful(remediate_context)
subject.lifecycle << ''
expect(subject).not_to be_valid
end
end
context 'ignored_as_duplicate validation' do
before do
subject.mark_as_unsuccessful(remediate_context)
end
it 'is invalid if remediation_type is ignored_as_duplicate and success is false' do
subject.remediation_type = :ignored_as_duplicate
subject.success = false
expect(subject).not_to be_valid
end
it 'is valid if ignored_as_duplicate is true and success is true' do
subject.remediation_type = :ignored_as_duplicate
subject.success = true
expect(subject).to be_valid
end
end
end
describe 'instance methods' do
describe '#mark_as_unsuccessful' do
let(:timestamped_context) { "#{Time.current.strftime('%Y-%m-%d %H:%M:%S')} -- #{remediate_context}" }
it 'transitions the record to success: false' do
subject.mark_as_unsuccessful(remediate_context)
expect(subject.success).to be false
end
it 'adds timestamped context to lifecycle' do
subject.mark_as_unsuccessful(remediate_context)
expect(subject.lifecycle.last).to match(timestamped_context)
end
it 'logs the change to Datadog' do
allow(StatsD).to receive(:increment)
subject.mark_as_unsuccessful(remediate_context)
expect(StatsD).to have_received(:increment).with(
"#{Form526SubmissionRemediation::STATSD_KEY_PREFIX} marked as unsuccessful: #{remediate_context}"
)
end
it 'adds an error if context is not a non-empty string and does not update lifecycle' do
subject.save
original_lifecycle = subject.lifecycle.dup
subject.mark_as_unsuccessful('')
expect(subject.errors[:base]).to include('Context must be a non-empty string')
expect(subject.lifecycle).to eq(original_lifecycle)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_action_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserAction, type: :model do
describe 'associations' do
it { is_expected.to belong_to(:acting_user_verification).class_name('UserVerification').optional }
it { is_expected.to belong_to(:subject_user_verification).class_name('UserVerification') }
it { is_expected.to belong_to(:user_action_event) }
end
describe 'enum status' do
it {
expect(subject).to define_enum_for(:status).with_values({ initial: 'initial',
success: 'success',
error: 'error' }).backed_by_column_of_type(:enum)
}
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_acceptable_verified_credential_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe UserAcceptableVerifiedCredential, type: :model do
subject do
create(:user_acceptable_verified_credential,
user_account:,
acceptable_verified_credential_at:,
idme_verified_credential_at:)
end
let(:user_account) { create(:user_account) }
let(:acceptable_verified_credential_at) { nil }
let(:idme_verified_credential_at) { nil }
describe 'validations' do
context 'when user_account is nil' do
let(:user_account) { nil }
let(:expected_error_message) { 'Validation failed: User account must exist' }
let(:expected_error) { ActiveRecord::RecordInvalid }
it 'raises validation error' do
expect { subject }.to raise_error(expected_error, expected_error_message)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/user_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'mhv/account_creation/service'
RSpec.describe User, type: :model do
subject { described_class.new(build(:user, loa:)) }
let(:loa) { loa_one }
let(:loa_one) { { current: LOA::ONE, highest: LOA::ONE } }
let(:loa_three) { { current: LOA::THREE, highest: LOA::THREE } }
let(:user) { build(:user, :loa3) }
describe '#icn' do
let(:user) { build(:user, icn: identity_icn) }
let(:mpi_profile) { build(:mpi_profile, icn: mpi_icn) }
let(:identity_icn) { 'some_identity_icn' }
let(:mpi_icn) { 'some_mpi_icn' }
before do
allow(user).to receive(:mpi).and_return(mpi_profile)
end
context 'when icn on User Identity exists' do
let(:identity_icn) { 'some_identity_icn' }
it 'returns icn off the User Identity' do
expect(user.icn).to eq(identity_icn)
end
end
context 'when icn on identity does not exist' do
let(:identity_icn) { nil }
context 'and icn on MPI Data exists' do
let(:mpi_icn) { 'some_mpi_icn' }
it 'returns icn from the MPI Data' do
expect(user.icn).to eq(mpi_icn)
end
end
context 'and icn on MPI Data does not exist' do
let(:mpi_icn) { nil }
it 'returns nil' do
expect(user.icn).to be_nil
end
end
end
end
describe '#needs_accepted_terms_of_use' do
context 'when user is verified' do
let(:user) { build(:user, :loa3, needs_accepted_terms_of_use: nil) }
context 'and user has an associated current terms of use agreements' do
let!(:terms_of_use_agreement) { create(:terms_of_use_agreement, user_account: user.user_account) }
it 'does not return true' do
expect(user.needs_accepted_terms_of_use).to be_falsey
end
end
context 'and user does not have an associated current terms of use agreements' do
it 'returns true' do
expect(user.needs_accepted_terms_of_use).to be true
end
end
end
context 'when user is not verified' do
let(:user) { build(:user, :loa1) }
it 'does not return true' do
expect(user.needs_accepted_terms_of_use).to be_falsey
end
end
end
describe 'vet360_contact_info' do
let(:user) { build(:user, :loa3) }
context 'when obtaining user contact info' do
it 'returns VAProfileRedis::V2::ContactInformation info' do
contact_info = user.vet360_contact_info
expect(contact_info.class).to eq(VAProfileRedis::V2::ContactInformation)
expect(contact_info.response.class).to eq(VAProfile::ContactInformation::V2::PersonResponse)
expect(contact_info.mailing_address.class).to eq(VAProfile::Models::Address)
expect(contact_info.email.email_address).to eq(user.va_profile_email)
end
end
end
describe '#all_emails' do
let(:user) { build(:user, :loa3, vet360_id: '12345') }
let(:vet360_email) { user.vet360_contact_info.email.email_address }
context 'when vet360 is down' do
it 'returns user email' do
expect(user).to receive(:vet360_contact_info).and_raise('foo')
expect(user.all_emails).to eq([user.email])
end
end
context 'when vet360 email is the same as user email' do
it 'removes the duplicate email' do
allow(user).to receive(:email).and_return(vet360_email.upcase)
expect(user.all_emails).to eq([vet360_email])
end
end
it 'returns identity and vet360 emails' do
expect(user.all_emails).to eq([vet360_email, user.email])
end
end
describe '#ssn_mismatch?', :skip_mvi do
let(:mpi_ssn) { '918273384' }
let(:mpi_profile) { build(:mpi_profile, { ssn: mpi_ssn }) }
let(:user) { build(:user, :loa3, mpi_profile:) }
it 'returns true if user loa3?, and ssns dont match' do
expect(user).to be_ssn_mismatch
end
it 'returns false if user is not loa3?' do
allow(user.identity).to receive(:loa3?).and_return(false)
expect(user).not_to be_loa3
expect(user.ssn).not_to eq(mpi_ssn)
expect(user.ssn_mpi).to be_falsey
expect(user).not_to be_ssn_mismatch
end
context 'identity ssn is nil' do
let(:user) { build(:user, :loa3, ssn: nil, mpi_profile:) }
it 'returns false' do
expect(user).to be_loa3
expect(user.ssn).to eq(mpi_ssn)
expect(user.ssn_mpi).to be_truthy
expect(user).not_to be_ssn_mismatch
end
end
context 'mpi ssn is nil' do
let(:mpi_profile) { build(:mpi_profile, { ssn: nil }) }
it 'returns false' do
expect(user).to be_loa3
expect(user.ssn).to be_truthy
expect(user.ssn_mpi).to be_falsey
expect(user).not_to be_ssn_mismatch
end
end
context 'matched ssn' do
let(:user) { build(:user, :loa3) }
it 'returns false if identity & mpi ssns match' do
expect(user).to be_loa3
expect(user.ssn).to be_truthy
expect(user.ssn_mpi).to be_truthy
expect(user).not_to be_ssn_mismatch
end
end
end
describe '#can_prefill_va_profile?' do
it 'returns true if user has edipi or icn' do
expect(user.authorize(:va_profile, :access?)).to be(true)
end
it 'returns false if user doesnt have edipi or icn' do
expect(user).to receive(:edipi).and_return(nil)
expect(user.authorize(:va_profile, :access?)).to be(false)
end
end
describe '.create()' do
context 'with LOA 1' do
subject(:loa1_user) { described_class.new(build(:user, loa: loa_one)) }
it 'does not allow a blank uuid' do
loa1_user.uuid = ''
expect(loa1_user).not_to be_valid
expect(loa1_user.errors[:uuid].size).to be_positive
end
end
context 'with LOA 1, and no highest will raise an exception on UserIdentity' do
subject(:loa1_user) { described_class.new(build(:user, loa: { current: 1 })) }
it 'raises an exception' do
expect { loa1_user }.to raise_exception(Common::Exceptions::ValidationErrors)
end
end
end
it 'has a persisted attribute of false' do
expect(subject).not_to be_persisted
end
describe 'redis persistence' do
before { subject.save }
describe '#save' do
it 'sets persisted flag to true' do
expect(subject).to be_persisted
end
it 'sets the ttl countdown' do
expect(subject.ttl).to be_an(Integer)
expect(subject.ttl).to be_between(0, 86_400)
end
end
describe '.find' do
let(:found_user) { described_class.find(subject.uuid) }
it 'can find a saved user in redis' do
expect(found_user).to be_a(described_class)
expect(found_user.uuid).to eq(subject.uuid)
end
it 'expires and returns nil if user loaded from redis is invalid' do
allow_any_instance_of(described_class).to receive(:valid?).and_return(false)
expect(found_user).to be_nil
end
it 'returns nil if user was not found' do
expect(described_class.find('non-existant-uuid')).to be_nil
end
end
describe '#destroy' do
it 'can destroy a user in redis' do
expect(subject.destroy).to eq(1)
expect(described_class.find(subject.uuid)).to be_nil
end
end
describe 'validate_mpi_profile' do
let(:loa) { loa_three }
let(:id_theft_flag) { false }
let(:deceased_date) { nil }
before { stub_mpi(build(:mpi_profile, icn: user.icn, deceased_date:, id_theft_flag:)) }
context 'when the user is not loa3' do
let(:loa) { loa_one }
it 'does not attempt to validate the user mpi profile' do
expect(subject.validate_mpi_profile).to be_nil
end
end
context 'when the MPI profile has a deceased date' do
let(:deceased_date) { '20020202' }
let(:expected_error_message) { 'Death Flag Detected' }
it 'raises an MPI Account Locked error' do
expect { subject.validate_mpi_profile }
.to raise_error(MPI::Errors::AccountLockedError)
.with_message(expected_error_message)
end
end
context 'when the MPI profile has an identity theft flag' do
let(:id_theft_flag) { true }
let(:expected_error_message) { 'Theft Flag Detected' }
it 'raises an MPI Account Locked error' do
expect { subject.validate_mpi_profile }
.to raise_error(MPI::Errors::AccountLockedError)
.with_message(expected_error_message)
end
end
context 'when the MPI profile has no issues' do
it 'returns a nil value' do
expect(subject.validate_mpi_profile).to be_nil
end
end
end
describe 'invalidate_mpi_cache' do
let(:cache_exists) { true }
before { allow_any_instance_of(MPIData).to receive(:cached?).and_return(cache_exists) }
context 'when user is not loa3' do
let(:loa) { loa_one }
it 'does not attempt to clear the user mpi cache' do
expect_any_instance_of(MPIData).not_to receive(:destroy)
subject.invalidate_mpi_cache
end
end
context 'when user is loa3' do
let(:loa) { loa_three }
context 'and mpi object exists with cached mpi response' do
let(:cache_exists) { true }
it 'clears the user mpi cache' do
expect_any_instance_of(MPIData).to receive(:destroy)
subject.invalidate_mpi_cache
end
end
context 'and mpi object does not exist with cached mpi response' do
let(:cache_exists) { false }
it 'does not attempt to clear the user mpi cache' do
expect_any_instance_of(MPIData).not_to receive(:destroy)
subject.invalidate_mpi_cache
end
end
end
end
describe '#mpi_profile?' do
context 'when user has mpi profile' do
it 'returns true' do
expect(user.mpi_profile?).to be(true)
end
end
context 'when user does not have an mpi profile' do
let(:user) { build(:user) }
it 'returns false' do
expect(user.mpi_profile?).to be(false)
end
end
end
describe 'getter methods' do
context 'when saml user attributes available, icn is available, and user LOA3' do
let(:vet360_id) { '1234567' }
let(:mpi_profile) { build(:mpi_profile, { vet360_id: }) }
let(:user) { build(:user, :loa3, mpi_profile:) }
it 'fetches first_name from IDENTITY' do
expect(user.first_name).to be(user.identity.first_name)
end
it 'fetches middle_name from IDENTITY' do
expect(user.middle_name).to be(user.identity.middle_name)
end
it 'fetches last_name from IDENTITY' do
expect(user.last_name).to be(user.identity.last_name)
end
it 'fetches gender from IDENTITY' do
expect(user.gender).to be(user.identity.gender)
end
it 'fetches properly parsed birth_date from IDENTITY' do
expect(user.birth_date).to eq(Date.parse(user.identity.birth_date).iso8601)
end
it 'fetches ssn from IDENTITY' do
expect(user.ssn).to be(user.identity.ssn)
end
it 'fetches edipi from IDENTITY' do
user.identity.edipi = '001001999'
expect(user.edipi).to be(user.identity.edipi)
end
it 'has a vet360 id if one exists' do
expect(user.vet360_id).to eq(vet360_id)
end
end
context 'when saml user attributes blank and user LOA3' do
let(:mpi_profile) do
build(:mpi_profile, { edipi: '1007697216',
given_names: [Faker::Name.first_name, Faker::Name.first_name],
family_name: Faker::Name.last_name,
gender: Faker::Gender.short_binary_type.upcase })
end
let(:user) do
build(:user, :loa3, mpi_profile:,
edipi: nil, first_name: '', middle_name: '', last_name: '', gender: '')
end
it 'fetches edipi from MPI' do
expect(user.edipi).to eq(user.edipi_mpi)
end
it 'fetches first_name from MPI' do
expect(user.first_name).to eq(user.first_name_mpi)
end
it 'fetches middle_name from MPI' do
expect(user.middle_name).to eq(user.middle_name_mpi)
end
it 'fetches last_name from MPI' do
expect(user.last_name).to eq(user.last_name_mpi)
end
it 'fetches gender from MPI' do
expect(user.gender).to eq(user.gender_mpi)
end
end
context 'exclusively MPI sourced attributes' do
context 'address attributes' do
let(:user) { build(:user, :loa3, address: expected_address) }
let(:expected_address) do
{ street: '123 Colfax Ave',
street2: 'Unit 456',
city: 'Denver',
state: 'CO',
postal_code: '80203',
country: 'USA' }
end
it 'fetches preferred name from MPI' do
expect(user.preferred_name).to eq(user.preferred_name_mpi)
end
context 'user has an address' do
it 'returns mpi_profile\'s address as hash' do
expect(user.address).to eq(expected_address)
expect(user.address).to eq(user.send(:mpi_profile).address.attributes.deep_symbolize_keys)
end
it 'returns mpi_profile\'s address postal code' do
expect(user.postal_code).to eq(expected_address[:postal_code])
expect(user.postal_code).to eq(user.send(:mpi_profile).address.postal_code)
end
end
context 'user does not have an address' do
before { user.send(:mpi_profile).address = nil }
it 'returns a hash where all values are nil' do
expect(user.address).to eq(
{ street: nil, street2: nil, city: nil, state: nil, country: nil, postal_code: nil }
)
end
it 'returns nil postal code' do
expect(user.postal_code).to be_nil
end
end
end
describe '#birls_id' do
let(:user) { build(:user, :loa3, birls_id: mpi_birls_id) }
let(:mpi_birls_id) { 'some_mpi_birls_id' }
it 'returns birls_id from the MPI profile' do
expect(user.birls_id).to eq(mpi_birls_id)
expect(user.birls_id).to eq(user.send(:mpi_profile).birls_id)
end
end
context 'CERNER ids' do
let(:user) do
build(:user, :loa3,
cerner_id:, cerner_facility_ids:)
end
let(:cerner_id) { 'some-cerner-id' }
let(:cerner_facility_ids) { %w[123 456] }
it 'returns cerner_id from the MPI profile' do
expect(user.cerner_id).to eq(cerner_id)
expect(user.cerner_id).to eq(user.send(:mpi_profile).cerner_id)
end
it 'returns cerner_facility_ids from the MPI profile' do
expect(user.cerner_facility_ids).to eq(cerner_facility_ids)
expect(user.cerner_facility_ids).to eq(user.send(:mpi_profile).cerner_facility_ids)
end
end
describe '#edipi_mpi' do
let(:user) { build(:user, :loa3, edipi: expected_edipi) }
let(:expected_edipi) { '1234567890' }
it 'fetches edipi from MPI' do
expect(user.edipi_mpi).to eq(expected_edipi)
expect(user.edipi_mpi).to eq(user.send(:mpi_profile).edipi)
end
end
describe '#gender_mpi' do
let(:user) { build(:user, :loa3, gender: expected_gender) }
let(:expected_gender) { 'F' }
it 'fetches gender from MPI' do
expect(user.gender_mpi).to eq(expected_gender)
expect(user.gender_mpi).to eq(user.send(:mpi_profile).gender)
end
end
describe '#home_phone' do
let(:user) { build(:user, :loa3, home_phone:) }
let(:home_phone) { '315-867-5309' }
it 'returns home_phone from the MPI profile' do
expect(user.home_phone).to eq(home_phone)
expect(user.home_phone).to eq(user.send(:mpi_profile).home_phone)
end
end
context 'name attributes' do
let(:user) do
build(:user, :loa3,
first_name:, middle_name:, last_name:, suffix:)
end
let(:first_name) { 'some-first-name' }
let(:middle_name) { 'some-middle-name' }
let(:last_name) { 'some-last-name' }
let(:suffix) { 'some-suffix' }
let(:expected_given_names) { [first_name, middle_name] }
let(:expected_common_name) { "#{first_name} #{middle_name} #{last_name} #{suffix}" }
it 'fetches first_name from MPI' do
expect(user.first_name_mpi).to eq(first_name)
expect(user.first_name_mpi).to eq(user.send(:mpi_profile).given_names&.first)
end
it 'fetches last_name from MPI' do
expect(user.last_name_mpi).to eq(last_name)
expect(user.last_name_mpi).to eq(user.send(:mpi_profile).family_name)
end
it 'returns an expected generated common name string' do
expect(user.common_name).to eq(expected_common_name)
end
it 'fetches given_names from MPI' do
expect(user.given_names).to eq(expected_given_names)
expect(user.given_names).to eq(user.send(:mpi_profile).given_names)
end
it 'fetches suffix from MPI' do
expect(user.suffix).to eq(suffix)
expect(user.suffix).to eq(user.send(:mpi_profile).suffix)
end
end
describe '#mhv_correlation_id' do
let(:user) { build(:user, :loa3, mpi_profile:) }
let(:mhv_user_account) { build(:mhv_user_account, user_profile_id: mhv_account_id) }
let(:mpi_profile) { build(:mpi_profile, active_mhv_ids:) }
let(:mhv_account_id) { 'some-id' }
let(:active_mhv_ids) { [mhv_account_id] }
let(:needs_accepted_terms_of_use) { false }
context 'when the user is loa3' do
let(:user) { build(:user, :loa3, needs_accepted_terms_of_use:, mpi_profile:) }
context 'and the user has accepted the terms of use' do
let(:needs_accepted_terms_of_use) { false }
context 'and mhv_user_account is present' do
before do
allow(user).to receive(:mhv_user_account).and_return(mhv_user_account)
end
it 'returns the user_profile_id from the mhv_user_account' do
expect(user.mhv_correlation_id).to eq(mhv_account_id)
end
end
context 'and mhv_user_account is not present' do
before do
allow(user).to receive(:mhv_user_account).and_return(nil)
end
context 'and the user has one active_mhv_ids' do
it 'returns the active_mhv_id' do
expect(user.mhv_correlation_id).to eq(active_mhv_ids.first)
end
end
context 'and the user has multiple active_mhv_ids' do
let(:active_mhv_ids) { %w[some-id another-id] }
it 'returns nil' do
expect(user.mhv_correlation_id).to be_nil
end
end
end
end
context 'and the user has not accepted the terms of use' do
let(:needs_accepted_terms_of_use) { true }
it 'returns nil' do
expect(user.mhv_correlation_id).to be_nil
end
end
end
context 'when the user is not loa3' do
let(:user) { build(:user, needs_accepted_terms_of_use:) }
it 'returns nil' do
expect(user.mhv_correlation_id).to be_nil
end
end
end
describe '#mhv_ids' do
let(:user) { build(:user, :loa3) }
it 'fetches mhv_ids from MPI' do
expect(user.mhv_ids).to be(user.send(:mpi_profile).mhv_ids)
end
end
describe '#active_mhv_ids' do
let(:user) { build(:user, :loa3, active_mhv_ids:) }
let(:active_mhv_ids) { [mhv_id] }
let(:mhv_id) { 'some-mhv-id' }
it 'fetches active_mhv_ids from MPI' do
expect(user.active_mhv_ids).to eq(active_mhv_ids)
end
context 'when user has duplicate ids' do
let(:active_mhv_ids) { [mhv_id, mhv_id] }
let(:expected_active_mhv_ids) { [mhv_id] }
it 'fetches unique active_mhv_ids from MPI' do
expect(user.active_mhv_ids).to eq(expected_active_mhv_ids)
end
end
end
describe '#participant_id' do
let(:user) { build(:user, :loa3, participant_id: mpi_participant_id) }
let(:mpi_participant_id) { 'some_mpi_participant_id' }
it 'returns participant_id from the MPI profile' do
expect(user.participant_id).to eq(mpi_participant_id)
expect(user.participant_id).to eq(user.send(:mpi_profile).participant_id)
end
end
describe '#person_types' do
let(:user) { build(:user, :loa3, person_types: expected_person_types) }
let(:expected_person_types) { %w[DEP VET] }
it 'returns person_types from the MPI profile' do
expect(user.person_types).to eq(expected_person_types)
expect(user.person_types).to eq(user.send(:mpi_profile).person_types)
end
end
describe '#ssn_mpi' do
let(:user) { build(:user, :loa3, ssn: expected_ssn) }
let(:expected_ssn) { '296333851' }
it 'returns ssn from the MPI profile' do
expect(user.ssn_mpi).to eq(expected_ssn)
expect(user.ssn_mpi).to eq(user.send(:mpi_profile).ssn)
end
end
context 'VHA facility ids' do
let(:user) do
build(:user, :loa3,
vha_facility_ids:, vha_facility_hash:)
end
let(:vha_facility_ids) { %w[200CRNR 200MHV] }
let(:vha_facility_hash) { { '200CRNR' => %w[123456], '200MHV' => %w[123456] } }
it 'returns vha_facility_ids from the MPI profile' do
expect(user.vha_facility_ids).to eq(vha_facility_ids)
expect(user.vha_facility_ids).to eq(user.send(:mpi_profile).vha_facility_ids)
end
it 'returns vha_facility_hash from the MPI profile' do
expect(user.vha_facility_hash).to eq(vha_facility_hash)
expect(user.vha_facility_hash).to eq(user.send(:mpi_profile).vha_facility_hash)
end
end
end
describe '#vha_facility_hash' do
let(:vha_facility_hash) { { '400' => %w[123456789 999888777] } }
let(:mpi_profile) { build(:mpi_profile, { vha_facility_hash: }) }
let(:user) { build(:user, :loa3, vha_facility_hash: nil, mpi_profile:) }
it 'returns the users vha_facility_hash' do
expect(user.vha_facility_hash).to eq(vha_facility_hash)
end
end
describe 'set_mhv_ids do' do
before { user.set_mhv_ids('1234567890') }
it 'sets new mhv ids to a users MPI profile' do
expect(user.mhv_ids).to include('1234567890')
expect(user.active_mhv_ids).to include('1234567890')
end
end
context 'when saml user attributes NOT available, icn is available, and user LOA3' do
let(:given_names) { [Faker::Name.first_name] }
let(:mpi_profile) { build(:mpi_profile, given_names:) }
let(:user) do
build(:user, :loa3, mpi_profile:,
first_name: nil, last_name: nil, birth_date: nil, ssn: nil, gender: nil, address: nil)
end
it 'fetches first_name from MPI' do
expect(user.first_name).to be(user.first_name_mpi)
end
context 'when given_names has no middle_name' do
it 'fetches middle name from MPI' do
expect(user.middle_name).to be_nil
end
end
context 'when given_names has middle_name' do
let(:given_names) { [Faker::Name.first_name, Faker::Name.first_name] }
it 'fetches middle name from MPI' do
expect(user.middle_name).to eq(given_names[1])
end
end
context 'when given_names has multiple middle names' do
let(:given_names) { [Faker::Name.first_name, Faker::Name.first_name, Faker::Name.first_name] }
let(:expected_middle_names) { given_names.drop(1).join(' ') }
it 'fetches middle name from MPI' do
expect(user.middle_name).to eq(expected_middle_names)
end
end
it 'fetches last_name from MPI' do
expect(user.last_name).to be(user.last_name_mpi)
end
it 'fetches gender from MPI' do
expect(user.gender).to be(user.gender_mpi)
end
it 'fetches properly parsed birth_date from MPI' do
expect(user.birth_date).to eq(Date.parse(user.birth_date_mpi).iso8601)
end
it 'fetches address data from MPI and stores it as a hash' do
expect(user.address[:street]).to eq(mpi_profile.address.street)
expect(user.address[:street2]).to be(mpi_profile.address.street2)
expect(user.address[:city]).to be(mpi_profile.address.city)
expect(user.address[:postal_code]).to be(mpi_profile.address.postal_code)
expect(user.address[:country]).to be(mpi_profile.address.country)
end
it 'fetches ssn from MPI' do
expect(user.ssn).to be(user.ssn_mpi)
end
end
context 'when saml user attributes NOT available, icn is available, and user NOT LOA3' do
let(:mpi_profile) { build(:mpi_profile) }
let(:user) do
build(:user, :loa1, mpi_profile:, mhv_icn: mpi_profile.icn,
first_name: nil, last_name: nil, birth_date: nil, ssn: nil, gender: nil, address: nil)
end
it 'fetches first_name from IDENTITY' do
expect(user.first_name).to be_nil
end
it 'fetches middle_name from IDENTITY' do
expect(user.middle_name).to be_nil
end
it 'fetches last_name from IDENTITY' do
expect(user.last_name).to be_nil
end
it 'fetches gender from IDENTITY' do
expect(user.gender).to be_nil
end
it 'fetches birth_date from IDENTITY' do
expect(user.birth_date).to be_nil
end
it 'fetches ssn from IDENTITY' do
expect(user.ssn).to be_nil
end
end
context 'when icn is not available from saml data' do
it 'fetches first_name from IDENTITY' do
expect(user.first_name).to be(user.identity.first_name)
end
it 'fetches middle_name from IDENTITY' do
expect(user.middle_name).to be(user.identity.middle_name)
end
it 'fetches last_name from IDENTITY' do
expect(user.last_name).to be(user.identity.last_name)
end
it 'fetches gender from IDENTITY' do
expect(user.gender).to be(user.identity.gender)
end
it 'fetches properly parsed birth_date from IDENTITY' do
expect(user.birth_date).to eq(Date.parse(user.identity.birth_date).iso8601)
end
it 'fetches ssn from IDENTITY' do
expect(user.ssn).to be(user.identity.ssn)
end
end
end
end
describe '#flipper_id' do
it 'returns a unique identifier of email' do
expect(user.flipper_id).to eq(user.email)
end
end
describe '#va_patient?' do
let(:user) { build(:user, :loa3, vha_facility_ids:) }
let(:vha_facility_ids) { [] }
around do |example|
with_settings(Settings.mhv, facility_range: [[450, 758]]) do
with_settings(Settings.mhv, facility_specific: ['759MM']) do
example.run
end
end
end
context 'when there are no facilities' do
it 'is false' do
expect(user).not_to be_va_patient
end
end
context 'when there are nil facilities' do
let(:vha_facility_ids) { nil }
it 'is false' do
expect(user).not_to be_va_patient
end
end
context 'when there are no facilities in the defined range' do
let(:vha_facility_ids) { [200, 759] }
it 'is false' do
expect(user).not_to be_va_patient
end
end
context 'when facility is at the bottom edge of range' do
let(:vha_facility_ids) { [450] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when alphanumeric facility is at the bottom edge of range' do
let(:vha_facility_ids) { %w[450MH] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when facility is at the top edge of range' do
let(:vha_facility_ids) { [758] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when alphanumeric facility is at the top edge of range' do
let(:vha_facility_ids) { %w[758MH] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when there are multiple alphanumeric facilities all within defined range' do
let(:vha_facility_ids) { %w[450MH 758MH] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when there are multiple facilities all outside of defined range' do
let(:vha_facility_ids) { %w[449MH 759MH] }
it 'is false' do
expect(user).not_to be_va_patient
end
end
context 'when it matches exactly to a facility_specific' do
let(:vha_facility_ids) { %w[759MM] }
it 'is true' do
expect(user).to be_va_patient
end
end
context 'when it does not match exactly to a facility_specific and is outside of ranges' do
let(:vha_facility_ids) { %w[759] }
it 'is false' do
expect(user).not_to be_va_patient
end
end
end
describe '#va_treatment_facility_ids' do
let(:vha_facility_ids) { %w[200MHS 400 741 744 741MM] }
let(:mpi_profile) { build(:mpi_profile, { vha_facility_ids: }) }
let(:user) { build(:user, :loa3, vha_facility_ids: nil, mpi_profile:) }
it 'filters out fake vha facility ids that arent in Settings.mhv.facility_range' do
expect(user.va_treatment_facility_ids).to match_array(%w[400 744 741MM])
end
end
describe '#birth_date' do
let(:user) { subject }
context 'when birth_date attribute is available on the UserIdentity object' do
it 'returns iso8601 parsed date from the UserIdentity birth_date attribute' do
expect(user.birth_date).to eq Date.parse(user.identity.birth_date.to_s).iso8601
end
end
context 'when birth_date attribute is not available on the UserIdentity object' do
before do
allow(user.identity).to receive(:birth_date).and_return nil
end
context 'and mhv_icn attribute is available on the UserIdentity object' do
let(:mpi_profile) { build(:mpi_profile) }
let(:user) { described_class.new(build(:user, :mhv, mhv_icn: 'some-mhv-icn', mpi_profile:)) }
context 'and MPI Profile birth date does not exist' do
let(:mpi_profile) { build(:mpi_profile, { birth_date: nil }) }
it 'returns nil' do
expect(user.birth_date).to be_nil
end
end
context 'and MPI Profile birth date does exist' do
it 'returns iso8601 parsed date from the MPI Profile birth_date attribute' do
expect(user.birth_date).to eq Date.parse(user.birth_date_mpi.to_s).iso8601
end
end
end
context 'when birth_date attribute cannot be retrieved from UserIdentity or MPI object' do
before do
allow(user.identity).to receive(:birth_date).and_return nil
end
it 'returns nil' do
expect(user.birth_date).to be_nil
end
end
end
end
describe '#deceased_date' do
let!(:user) { described_class.new(build(:user, :mhv, mhv_icn: 'some-mhv-icn')) }
context 'and MPI Profile deceased date does not exist' do
before do
allow_any_instance_of(MPI::Models::MviProfile).to receive(:deceased_date).and_return nil
end
it 'returns nil' do
expect(user.deceased_date).to be_nil
end
end
context 'and MPI Profile deceased date does exist' do
let(:mpi_profile) { build(:mpi_profile, deceased_date:) }
let(:deceased_date) { '20200202' }
before do
stub_mpi(mpi_profile)
end
it 'returns iso8601 parsed date from the MPI Profile deceased_date attribute' do
expect(user.deceased_date).to eq Date.parse(deceased_date).iso8601
end
end
end
describe '#relationships' do
let(:user) { described_class.new(build(:user_with_relationship)) }
before do
allow_any_instance_of(MPI::Models::MviProfile).to receive(:relationships).and_return(mpi_relationship_array)
end
context 'when user is not loa3' do
let(:user) { described_class.new(build(:user, :loa1)) }
let(:mpi_relationship_array) { [] }
it 'returns nil' do
expect(user.relationships).to be_nil
end
end
context 'when user is loa3' do
context 'when there are relationship entities in the MPI response' do
let(:mpi_relationship_array) { [mpi_relationship] }
let(:mpi_relationship) { build(:mpi_profile_relationship) }
let(:user_relationship_double) { double }
let(:expected_user_relationship_array) { [user_relationship_double] }
before do
allow(UserRelationship).to receive(:from_mpi_relationship)
.with(mpi_relationship).and_return(user_relationship_double)
end
it 'returns an array of UserRelationship objects representing the relationship entities' do
expect(user.relationships).to eq expected_user_relationship_array
end
end
context 'when there are not relationship entities in the MPI response' do
let(:mpi_relationship_array) { nil }
let(:bgs_dependent_response) { nil }
before do
allow_any_instance_of(BGS::DependentService).to receive(:get_dependents).and_return(bgs_dependent_response)
end
it 'makes a call to the BGS for relationship information' do
expect_any_instance_of(BGS::DependentService).to receive(:get_dependents)
user.relationships
end
context 'when BGS relationship response contains information' do
let(:bgs_relationship_array) { [bgs_dependent] }
let(:bgs_dependent) do
{
'award_indicator' => 'N',
'city_of_birth' => 'WASHINGTON',
'current_relate_status' => '',
'date_of_birth' => '01/01/2000',
'date_of_death' => '',
'death_reason' => '',
'email_address' => 'Curt@email.com',
'first_name' => 'CURT',
'gender' => '',
'last_name' => 'WEBB-STER',
'middle_name' => '',
'proof_of_dependency' => 'Y',
'ptcpnt_id' => '32354974',
'related_to_vet' => 'N',
'relationship' => 'Child',
'ssn' => '500223351',
'ssn_verify_status' => '1',
'state_of_birth' => 'DC'
}
end
let(:bgs_dependent_response) { { persons: [bgs_dependent] } }
let(:user_relationship_double) { double }
let(:expected_user_relationship_array) { [user_relationship_double] }
before do
allow(UserRelationship).to receive(:from_bgs_dependent)
.with(bgs_dependent).and_return(user_relationship_double)
end
it 'returns an array of UserRelationship objects representing the relationship entities' do
expect(user.relationships).to eq expected_user_relationship_array
end
end
context 'when BGS relationship response does not contain information' do
it 'returns an empty array' do
expect(user.relationships).to be_nil
end
end
end
end
end
describe '#fingerprint' do
let(:fingerprint) { '196.168.0.0' }
let(:user) { create(:user, fingerprint:) }
it 'returns expected user fingerprint' do
expect(user.fingerprint).to eq(fingerprint)
end
context 'fingerprint mismatch' do
let(:new_fingerprint) { '0.0.0.0' }
it 'can update the user fingerprint value' do
user.fingerprint = new_fingerprint
expect(user.fingerprint).to eq(new_fingerprint)
end
end
end
context 'user_verification methods' do
let(:user) do
described_class.new(
build(:user, :loa3, uuid:,
idme_uuid:, logingov_uuid:,
edipi:, mhv_credential_uuid:, authn_context:, icn:, user_verification:)
)
end
let(:authn_context) { LOA::IDME_LOA1_VETS }
let(:csp) { 'idme' }
let(:logingov_uuid) { 'some-logingov-uuid' }
let(:idme_uuid) { 'some-idme-uuid' }
let(:edipi) { 'some-edipi' }
let(:mhv_credential_uuid) { 'some-mhv-credential-uuid' }
let(:icn) { 'some-icn' }
let!(:user_verification) do
Login::UserVerifier.new(login_type: csp,
auth_broker: 'iam',
mhv_uuid: mhv_credential_uuid,
idme_uuid:,
dslogon_uuid: edipi,
logingov_uuid:,
icn:).perform
end
let!(:user_account) { user_verification&.user_account }
let(:uuid) { user_account.id }
describe '#user_verification' do
it 'returns expected user_verification' do
expect(user.user_verification).to eq(user_verification)
end
context 'when user is logged in with mhv' do
let(:csp) { 'mhv' }
let(:authn_context) { 'myhealthevet' }
context 'and there is an mhv_credential_uuid' do
it 'returns user verification with a matching mhv_credential_uuid' do
expect(user.user_verification.mhv_uuid).to eq(mhv_credential_uuid)
end
end
context 'and there is not an mhv_credential_uuid' do
let(:mhv_credential_uuid) { nil }
context 'and user has an idme_uuid' do
let(:idme_uuid) { 'some-idme-uuid' }
it 'returns user verification with a matching idme_uuid' do
expect(user.user_verification.idme_uuid).to eq(idme_uuid)
end
end
context 'and user does not have an idme_uuid' do
let(:idme_uuid) { nil }
let(:user_verification) { nil }
let(:uuid) { SecureRandom.uuid }
it 'returns nil' do
expect(user.user_verification).to be_nil
end
end
end
end
context 'when user is logged in with dslogon' do
let(:csp) { 'dslogon' }
let(:authn_context) { 'dslogon' }
context 'and there is an edipi' do
let(:edipi) { 'some-edipi' }
it 'returns user verification with a matching edipi' do
expect(user.user_verification.dslogon_uuid).to eq(edipi)
end
end
context 'and there is not an edipi' do
let(:edipi) { nil }
context 'and user has an idme_uuid' do
let(:idme_uuid) { 'some-idme-uuid' }
it 'returns user verification with a matching idme_uuid' do
expect(user.user_verification.idme_uuid).to eq(idme_uuid)
end
end
context 'and user does not have an idme_uuid' do
let(:idme_uuid) { nil }
let(:user_verification) { nil }
let(:uuid) { SecureRandom.uuid }
it 'returns nil' do
expect(user.user_verification).to be_nil
end
end
end
end
context 'when user is logged in with logingov' do
let(:authn_context) { IAL::LOGIN_GOV_IAL1 }
let(:csp) { 'logingov' }
it 'returns user verification with a matching logingov uuid' do
expect(user.user_verification.logingov_uuid).to eq(logingov_uuid)
end
end
context 'when user is logged in with idme' do
let(:authn_context) { LOA::IDME_LOA1_VETS }
context 'and user has an idme_uuid' do
let(:idme_uuid) { 'some-idme-uuid' }
it 'returns user verification with a matching idme_uuid' do
expect(user.user_verification.idme_uuid).to eq(idme_uuid)
end
end
context 'and user does not have an idme_uuid' do
let(:idme_uuid) { nil }
let(:user_verification) { nil }
let(:uuid) { SecureRandom.uuid }
it 'returns nil' do
expect(user.user_verification).to be_nil
end
end
end
end
describe '#user_account' do
it 'returns expected user_account' do
expect(user.user_account).to eq(user_account)
end
end
describe '#credential_lock' do
context 'when the user has a UserVerification' do
let(:user_verification) { create(:idme_user_verification, locked:) }
let(:user) { build(:user, :loa3, user_verification:, idme_uuid: user_verification.idme_uuid) }
let(:locked) { false }
context 'when the UserVerification is not locked' do
it 'returns false' do
expect(user.credential_lock).to be(false)
end
end
context 'when the UserVerification is locked' do
let(:locked) { true }
it 'returns true' do
expect(user.credential_lock).to be(true)
end
end
end
context 'when the user does not have a UserVerification' do
let(:user) { build(:user, :loa1, uuid: SecureRandom.uuid, user_verification: nil) }
it 'returns nil' do
expect(user.credential_lock).to be_nil
end
end
end
end
describe '#onboarding' do
let(:user) { create(:user) }
before do
Flipper.enable(:veteran_onboarding_beta_flow, user)
Flipper.disable(:veteran_onboarding_show_to_newly_onboarded)
end
context "when feature toggle is enabled, show onboarding flow depending on user's preferences" do
it 'show_onboarding_flow_on_login returns true when flag is enabled and display_onboarding_flow is true' do
expect(user.show_onboarding_flow_on_login).to be true
end
it 'show_onboarding_flow_on_login returns false when flag is enabled but display_onboarding_flow is false' do
user.onboarding.display_onboarding_flow = false
expect(user.show_onboarding_flow_on_login).to be false
end
end
context 'when feature toggle is disabled, never show onboarding flow' do
it 'show_onboarding_flow_on_login returns false when flag is disabled, even if display_onboarding_flow is true' do
Flipper.disable(:veteran_onboarding_beta_flow)
Flipper.disable(:veteran_onboarding_show_to_newly_onboarded)
expect(user.show_onboarding_flow_on_login).to be_falsey
end
end
end
describe '#mhv_user_account' do
subject { user.mhv_user_account(from_cache_only:) }
let(:user) { build(:user, :loa3) }
let(:icn) { user.icn }
let(:expected_cache_key) { "mhv_account_creation_#{icn}" }
let(:user_account) { user.user_account }
let!(:terms_of_use_agreement) { create(:terms_of_use_agreement, user_account:, response: terms_of_use_response) }
let(:terms_of_use_response) { 'accepted' }
let(:mhv_client) { MHV::AccountCreation::Service.new }
let(:mhv_response) do
{
user_profile_id: '12345678',
premium: true,
champ_va: true,
patient: true,
sm_account_created: true,
message: 'some-message'
}
end
let(:from_cache_only) { true }
before do
allow(Rails.logger).to receive(:info)
allow(MHV::AccountCreation::Service).to receive(:new).and_return(mhv_client)
allow(Rails.cache).to receive(:read).with(expected_cache_key).and_return(mhv_response)
end
context 'when from_cache_only is true' do
let(:from_cache_only) { true }
context 'and the mhv response is cached' do
context 'when the user has all required attributes' do
it 'returns a MHVUserAccount with the expected attributes' do
mhv_user_account = subject
expect(mhv_user_account).to be_a(MHVUserAccount)
expect(mhv_user_account.attributes).to eq(mhv_response.with_indifferent_access)
end
end
context 'and there is an error creating the account' do
shared_examples 'mhv_user_account error' do
let(:expected_log_message) { '[User] mhv_user_account error' }
let(:expected_log_payload) { { error_message: /#{expected_error_message}/, icn: user.icn } }
it 'logs and returns nil' do
expect(subject).to be_nil
expect(Rails.logger).to have_received(:info).with(expected_log_message, expected_log_payload)
end
end
context 'and the user does not have a terms_of_use_agreement' do
let(:terms_of_use_agreement) { nil }
let(:expected_error_message) { 'Current terms of use agreement must be present' }
it_behaves_like 'mhv_user_account error'
end
context 'and the user has not accepted the terms of use' do
let(:terms_of_use_response) { 'declined' }
let(:expected_error_message) { "Current terms of use agreement must be 'accepted'" }
it_behaves_like 'mhv_user_account error'
end
context 'and the user does not have an icn' do
let(:user) { build(:user, :loa3, icn: nil) }
let(:expected_error_message) { 'ICN must be present' }
it_behaves_like 'mhv_user_account error'
end
end
end
context 'and the mhv response is not cached' do
let(:mhv_response) { nil }
it 'returns nil' do
expect(subject).to be_nil
end
end
end
context 'when from_cache_only is false' do
let(:from_cache_only) { false }
let(:mhv_service_response) do
{
user_profile_id: '12345678',
premium: true,
champ_va: true,
patient: true,
sm_account_created: true,
message: 'some-message'
}
end
before do
allow_any_instance_of(MHV::AccountCreation::Service)
.to receive(:create_account)
.and_return(mhv_service_response)
end
context 'and the mhv response is cached' do
context 'when the user has all required attributes' do
it 'returns a MHVUserAccount with the expected attributes' do
mhv_user_account = subject
expect(mhv_user_account).to be_a(MHVUserAccount)
expect(mhv_user_account.attributes).to eq(mhv_response.with_indifferent_access)
end
end
context 'and there is an error creating the account' do
shared_examples 'mhv_user_account error' do
let(:expected_log_message) { '[User] mhv_user_account error' }
let(:expected_log_payload) { { error_message: /#{expected_error_message}/, icn: user.icn } }
it 'logs and returns nil' do
expect(subject).to be_nil
expect(Rails.logger).to have_received(:info).with(expected_log_message, expected_log_payload)
end
end
context 'and the user does not have a terms_of_use_agreement' do
let(:terms_of_use_agreement) { nil }
let(:expected_error_message) { 'Current terms of use agreement must be present' }
it_behaves_like 'mhv_user_account error'
end
context 'and the user has not accepted the terms of use' do
let(:terms_of_use_response) { 'declined' }
let(:expected_error_message) { "Current terms of use agreement must be 'accepted'" }
it_behaves_like 'mhv_user_account error'
end
context 'and the user does not have an icn' do
let(:user) { build(:user, :loa3, icn: nil) }
let(:expected_error_message) { 'ICN must be present' }
it_behaves_like 'mhv_user_account error'
end
end
end
context 'and the mhv response is not cached' do
let(:mhv_response) { nil }
it 'returns result of calling MHV Account Creation Service' do
expect(subject.attributes).to eq(mhv_service_response.with_indifferent_access)
end
end
end
end
describe '#create_mhv_account_async' do
let(:user) { build(:user, :loa3, needs_accepted_terms_of_use:) }
let(:needs_accepted_terms_of_use) { false }
let(:user_verification) { user.user_verification }
before { allow(MHV::AccountCreatorJob).to receive(:perform_async) }
context 'when the user is loa3' do
let(:user) { build(:user, :loa3, needs_accepted_terms_of_use:) }
context 'and the user has accepted the terms of use' do
let(:needs_accepted_terms_of_use) { false }
it 'enqueues a job to create the MHV account' do
user.create_mhv_account_async
expect(MHV::AccountCreatorJob).to have_received(:perform_async).with(user_verification.id)
end
end
context 'and the user has not accepted the terms of use' do
let(:needs_accepted_terms_of_use) { true }
it 'does not enqueue a job to create the MHV account' do
user.create_mhv_account_async
expect(MHV::AccountCreatorJob).not_to have_received(:perform_async)
end
end
end
context 'when the user is not loa3' do
let(:user) { build(:user, needs_accepted_terms_of_use:) }
it 'does not enqueue a job to create the MHV account' do
user.create_mhv_account_async
expect(MHV::AccountCreatorJob).not_to have_received(:perform_async)
end
end
end
describe '#provision_cerner_async' do
let(:user) { build(:user, :loa3, cerner_id:, cerner_facility_ids:) }
let(:cerner_id) { 'some-cerner-id' }
let(:cerner_facility_ids) { ['some-cerner-facility-id'] }
before do
allow(Identity::CernerProvisionerJob).to receive(:perform_async)
end
context 'when the user is loa3' do
context 'when the user has a cerner_id' do
it 'enqueues a job to provision the Cerner account' do
user.provision_cerner_async
expect(Identity::CernerProvisionerJob).to have_received(:perform_async).with(user.icn, nil)
end
end
context 'when the user does not have a cerner_id nor cerner_facility_ids' do
let(:cerner_id) { nil }
let(:cerner_facility_ids) { [] }
it 'does not enqueue a job to provision the Cerner account' do
user.provision_cerner_async
expect(Identity::CernerProvisionerJob).not_to have_received(:perform_async)
end
end
end
context 'when the user is not loa3' do
let(:user) { build(:user, cerner_id:) }
it 'does not enqueue a job to provision the Cerner account' do
user.provision_cerner_async
expect(Identity::CernerProvisionerJob).not_to have_received(:perform_async)
end
end
end
describe '#cerner_eligible?' do
let(:user) { build(:user, :loa3, cerner_id:) }
context 'when the user is loa3' do
context 'when the user has a cerner_id' do
let(:cerner_id) { 'some-cerner-id' }
it 'returns true' do
expect(user.cerner_eligible?).to be true
end
end
context 'when the user does not have a cerner_id' do
let(:cerner_id) { nil }
it 'returns false' do
expect(user.cerner_eligible?).to be false
end
end
end
context 'when the user is not loa3' do
let(:user) { build(:user) }
it 'returns false' do
expect(user.cerner_eligible?).to be false
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/excel_file_event_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe ExcelFileEvent, type: :model do
subject { described_class.new }
it 'validates filename uniqueness' do
create(:excel_file_event, filename: 'test_file.csv')
duplicate = build(:excel_file_event, filename: 'test_file.csv')
expect(duplicate.valid?).to be(false)
end
describe 'build_event' do
before do
ExcelFileEvent.delete_all
end
it 'returns a successful existing event' do
successful_event = create(:excel_file_event, :successful)
event = ExcelFileEvent.build_event(successful_event.filename)
expect(successful_event.id).to eq(event.id)
expect(successful_event.filename).to eq(event.filename)
end
it 'returns a non-successful existing event with incremented retry attempt' do
non_successful_event = create(:excel_file_event)
event = ExcelFileEvent.build_event(non_successful_event.filename)
expect(non_successful_event.id).to eq(event.id)
expect(event.retry_attempt).to eq(non_successful_event.retry_attempt + 1)
end
it 'returns a new event when filename pattern does not match existing events' do
filename = "22-10282_#{Time.zone.now.strftime('%Y%m%d')}.csv"
event = ExcelFileEvent.build_event(filename)
expect(event.filename).to eq(filename)
expect(event.retry_attempt).to eq(0)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/mpi_data_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe MPIData, :skip_mvi do
let(:user) { build(:user, :loa3, :no_mpi_profile) }
describe '.for_user' do
subject { MPIData.for_user(user.identity) }
it 'creates an instance with given user identity attributes' do
mpi_data = subject
expect(mpi_data.user_loa3).to eq(user.identity.loa3?)
expect(mpi_data.user_icn).to eq(user.identity.icn)
expect(mpi_data.user_first_name).to eq(user.identity.first_name)
expect(mpi_data.user_last_name).to eq(user.identity.last_name)
expect(mpi_data.user_birth_date).to eq(user.identity.birth_date)
expect(mpi_data.user_ssn).to eq(user.identity.ssn)
expect(mpi_data.user_edipi).to eq(user.identity.edipi)
expect(mpi_data.user_logingov_uuid).to eq(user.identity.logingov_uuid)
expect(mpi_data.user_idme_uuid).to eq(user.identity.idme_uuid)
expect(mpi_data.user_uuid).to eq(user.identity.uuid)
end
end
describe '#add_person_proxy' do
subject { mpi_data.add_person_proxy(as_agent:) }
let(:as_agent) { false }
let(:mpi_data) { MPIData.for_user(user.identity) }
let(:profile_response_error) { create(:find_profile_server_error_response) }
let(:profile_response) { create(:find_profile_response, profile: mpi_profile) }
let(:mpi_profile) { build(:mpi_profile) }
context 'with a successful add' do
let(:add_response) { create(:add_person_response, parsed_codes:) }
let(:parsed_codes) do
{
birls_id:,
participant_id:
}
end
let(:birls_id) { '111985523' }
let(:participant_id) { '32397028' }
let(:given_names) { %w[kitty] }
let(:family_name) { 'banana' }
let(:suffix) { 'Jr' }
let(:birth_date) { '19801010' }
let(:address) do
{
street: '1600 Pennsylvania Ave',
city: 'Washington',
state: 'DC',
country: 'USA',
postal_code: '20500'
}
end
let(:icn) { 'some-icn' }
let(:edipi) { 'some-edipi' }
let(:search_token) { 'some-search_token' }
let(:gender) { 'M' }
let(:ssn) { '987654321' }
let(:phone) { '(800) 867-5309' }
let(:person_types) { ['VET'] }
let(:mpi_profile) do
build(:mpi_profile,
given_names:,
family_name:,
birth_date:,
icn:,
edipi:,
search_token:,
ssn:,
person_types:,
gender:)
end
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes_with_orch_search)
.and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:add_person_proxy).and_return(add_response)
end
it 'creates a birls_id from add_person_proxy and adds it to existing mpi data object' do
expect { subject }.to change(mpi_data, :birls_id).from(user.birls_id).to(birls_id)
end
it 'creates a participant_id from add_person_proxy and adds it to existing mpi data object' do
expect { subject }.to change(mpi_data, :participant_id).from(user.participant_id).to(participant_id)
end
it 'copies relevant results from orchestration search to fields for add person call' do
subject
expect(mpi_data.birls_id).to eq(birls_id)
expect(mpi_data.participant_id).to eq(participant_id)
end
it 'clears the cached MPI response' do
mpi_data.status
expect(mpi_data).to be_mpi_response_is_cached
subject
expect(mpi_data).not_to be_mpi_response_is_cached
end
it 'returns the successful response' do
expect(subject.ok?).to be(true)
end
context 'with as_agent set to true' do
let(:as_agent) { true }
it 'returns the successful response' do
expect(subject.ok?).to be(true)
end
it 'calls add_person_proxy with as_agent set to true' do
expect_any_instance_of(MPI::Service).to receive(:add_person_proxy).with(
last_name: family_name,
ssn:,
birth_date:,
icn:,
edipi:,
search_token:,
first_name: given_names.first,
as_agent:
)
subject
end
end
end
context 'with a failed search' do
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes_with_orch_search)
.and_return(profile_response_error)
end
it 'returns the response from the failed search' do
expect_any_instance_of(MPI::Service).not_to receive(:add_person_proxy)
expect(subject).to eq(profile_response_error)
end
end
context 'with a failed add' do
let(:add_response_error) { create(:add_person_server_error_response) }
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes_with_orch_search)
.and_return(profile_response)
allow_any_instance_of(MPI::Service).to receive(:add_person_proxy).and_return(add_response_error)
end
it 'returns the failed add response' do
expect_any_instance_of(MPIData).not_to receive(:add_ids)
expect_any_instance_of(MPIData).not_to receive(:cache)
response = subject
expect(response.server_error?).to be(true)
end
end
end
describe '#profile' do
subject { mpi_data.profile }
let(:mpi_data) { MPIData.for_user(user.identity) }
context 'when user is not loa3' do
let(:user) { build(:user) }
it 'returns nil' do
expect(subject).to be_nil
end
end
context 'when user is loa3' do
let(:profile_response) { 'some-profile-response' }
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
end
context 'and there is cached data for a successful response' do
let(:mpi_profile) { build(:mpi_profile_response) }
let(:profile_response) { create(:find_profile_response, profile: mpi_profile) }
before { mpi_data.cache(user.uuid, profile_response) }
it 'returns the cached data' do
expect(MPIData.find(user.uuid).response).to have_deep_attributes(profile_response)
end
end
context 'and there is cached data for a server error response' do
let(:profile_response) { create(:find_profile_server_error_response) }
before { mpi_data.cache(user.uuid, profile_response) }
it 'returns the cached data' do
expect(MPIData.find(user.uuid).response).to have_deep_attributes(profile_response)
end
end
context 'and there is cached data for a not found response' do
let(:profile_response) { create(:find_profile_not_found_response) }
before { mpi_data.cache(user.uuid, profile_response) }
it 'returns the cached data' do
expect(MPIData.find(user.uuid).response).to have_deep_attributes(profile_response)
end
end
context 'and there is not cached data for a response' do
context 'and the response is successful' do
let(:mpi_profile) { build(:mpi_profile_response) }
let(:profile_response) { create(:find_profile_response, profile: mpi_profile) }
it 'returns the successful response' do
expect(subject).to eq(mpi_profile)
end
it 'caches the successful response' do
subject
expect(MPIData.find(user.icn).response).to have_deep_attributes(profile_response)
end
end
context 'and the response is not successful with not found response' do
let(:profile_response) { create(:find_profile_not_found_response, profile:) }
let(:profile) { 'some-unsuccessful-profile' }
it 'returns the unsuccessful response' do
expect(subject).to eq(profile)
end
it 'caches the unsuccessful response' do
subject
expect(MPIData.find(user.icn).response.profile).to eq(profile)
end
end
context 'and the response is not successful with server error response' do
let(:profile_response) { create(:find_profile_server_error_response, profile:) }
let(:profile) { 'some-unsuccessful-profile' }
it 'returns the unsuccessful response' do
expect(subject).to eq(profile)
end
it 'does not cache the unsuccessful response' do
subject
expect(MPIData.find(user.icn)).to be_nil
end
end
end
end
end
describe 'delegated attribute functions' do
context 'with a successful response' do
let(:mpi_data) { MPIData.for_user(user.identity) }
let(:mpi_profile) { build(:mpi_profile) }
let(:profile_response) { create(:find_profile_response, profile: mpi_profile) }
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response)
end
describe '#edipi' do
it 'matches the response' do
expect(mpi_data.edipi).to eq(profile_response.profile.edipi)
end
end
describe '#edipis' do
it 'matches the response' do
expect(mpi_data.edipis).to eq(profile_response.profile.edipis)
end
end
describe '#icn' do
it 'matches the response' do
expect(mpi_data.icn).to eq(profile_response.profile.icn)
end
end
describe '#icn_with_aaid' do
it 'matches the response' do
expect(mpi_data.icn_with_aaid).to eq(profile_response.profile.icn_with_aaid)
end
end
describe '#mhv_correlation_id' do
it 'matches the response' do
expect(mpi_data.mhv_correlation_id).to eq(profile_response.profile.mhv_correlation_id)
end
end
describe '#participant_id' do
it 'matches the response' do
expect(mpi_data.participant_id).to eq(profile_response.profile.participant_id)
end
end
describe '#participant_ids' do
it 'matches the response' do
expect(mpi_data.participant_ids).to eq(profile_response.profile.participant_ids)
end
end
describe '#birls_id' do
it 'matches the response' do
expect(mpi_data.birls_id).to eq(profile_response.profile.birls_id)
end
end
describe '#birls_ids' do
it 'matches the response' do
expect(mpi_data.birls_ids).to eq(profile_response.profile.birls_ids)
end
end
describe '#mhv_ien' do
it 'matches the response' do
expect(mpi_data.mhv_ien).to eq(profile_response.profile.mhv_ien)
end
end
describe '#mhv_iens' do
it 'matches the response' do
expect(mpi_data.mhv_iens).to eq(profile_response.profile.mhv_iens)
end
end
describe '#vet360_id' do
it 'matches the response' do
expect(mpi_data.vet360_id).to eq(profile_response.profile.vet360_id)
end
end
end
context 'with an error response' do
let(:mpi_data) { MPIData.for_user(user.identity) }
let(:profile_response_error) { create(:find_profile_server_error_response, error:) }
let(:error) { 'some-error' }
before do
allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(profile_response_error)
end
it 'captures the error in #error' do
expect(mpi_data.error).to eq(error)
end
describe '#edipi' do
it 'is nil' do
expect(mpi_data.edipi).to be_nil
end
end
describe '#icn' do
it 'is nil' do
expect(mpi_data.icn).to be_nil
end
end
describe '#icn_with_aaid' do
it 'is nil' do
expect(mpi_data.icn_with_aaid).to be_nil
end
end
describe '#mhv_correlation_id' do
it 'is nil' do
expect(mpi_data.mhv_correlation_id).to be_nil
end
end
describe '#participant_id' do
it 'is nil' do
expect(mpi_data.participant_id).to be_nil
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/accreditation_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Accreditation, type: :model do
describe 'validations' do
subject { build(:accreditation) }
it { is_expected.to belong_to(:accredited_individual) }
it { is_expected.to belong_to(:accredited_organization) }
it {
expect(subject).to validate_uniqueness_of(:accredited_organization_id)
.scoped_to(:accredited_individual_id)
.ignoring_case_sensitivity
}
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/models/saved_claim_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
class TestSavedClaim < SavedClaim
FORM = 'some_form_id'
CONFIRMATION = 'test'
def regional_office
'test_office'
end
def attachment_keys
%i[some_key]
end
end
RSpec.describe TestSavedClaim, type: :model do # rubocop:disable RSpec/SpecFilePathFormat
subject(:saved_claim) { described_class.new(form: form_data) }
let(:form_data) { { some_key: 'some_value' }.to_json }
let(:schema) { { some_key: 'some_value' }.to_json }
before do
allow(Flipper).to receive(:enabled?).with(:validate_saved_claims_with_json_schemer).and_return(false)
allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true)
allow(VetsJsonSchema::SCHEMAS).to receive(:[]).and_return(schema)
allow(JSON::Validator).to receive_messages(fully_validate_schema: [], fully_validate: [])
end
describe 'associations' do
it { is_expected.to have_many(:persistent_attachments).dependent(:destroy) }
it { is_expected.to have_many(:form_submissions).dependent(:nullify) }
it { is_expected.to have_many(:claim_va_notifications).dependent(:destroy) }
end
describe 'validations' do
context 'no validation errors' do
it 'returns true' do
expect(saved_claim.validate).to be(true)
end
end
context 'validation errors' do
let(:allowed_errors) do
{
data_pointer: 'data_pointer',
error: 'some error',
details: { detail: 'thing' },
schema: { detail: 'schema' },
root_schema: { detail: 'root_schema' }
}
end
let(:filtered_out_errors) { { data: { key: 'this could be pii' } } }
let(:schema_errors) { [allowed_errors.merge(filtered_out_errors)] }
let(:formatted_errors) { { message: 'some error', fragment: 'data_pointer' } }
let(:filtered_schema_errors) { [allowed_errors.merge(formatted_errors)] }
context 'when validate_schema returns errors' do
before do
allow(JSONSchemer).to receive_messages(validate_schema: schema_errors)
end
it 'logs schema failed error' do
expect(Rails.logger).to receive(:error)
.with('SavedClaim schema failed validation.', { errors: filtered_schema_errors,
form_id: saved_claim.form_id })
expect(saved_claim.validate).to be(true)
end
end
context 'when form validation returns errors' do
before do
allow(JSONSchemer).to receive_messages(validate_schema: [])
allow(JSONSchemer).to receive(:schema).and_return(double(:fake_schema,
validate: schema_errors))
end
it 'adds validation errors to the form' do
expect(Rails.logger).to receive(:error)
.with('SavedClaim form did not pass validation',
{ guid: saved_claim.guid, form_id: saved_claim.form_id, errors: filtered_schema_errors })
saved_claim.validate
expect(saved_claim.errors.full_messages).not_to be_empty
end
end
end
end
describe 'callbacks' do
let(:tags) { ["form_id:#{saved_claim.form_id}", "doctype:#{saved_claim.doctype}"] }
context 'after create' do
it 'increments the saved_claim.create metric' do
allow(StatsD).to receive(:increment)
saved_claim.save!
expect(StatsD).to have_received(:increment).with('saved_claim.create', tags:)
end
context 'if form_start_date is set' do
let(:form_start_date) { DateTime.now - 1 }
it 'increments the saved_claim.time-to-file metric' do
allow(StatsD).to receive(:measure)
saved_claim.form_start_date = form_start_date
saved_claim.save!
claim_duration = saved_claim.created_at - form_start_date
expect(StatsD).to have_received(:measure).with(
'saved_claim.time-to-file',
be_within(1.second).of(claim_duration),
tags:
)
end
end
context 'if form_id is not registered with PdfFill::Filler' do
it 'skips tracking pdf overflow' do
allow(StatsD).to receive(:increment)
saved_claim.save!
expect(StatsD).to have_received(:increment).with('saved_claim.create',
tags: ['form_id:SOME_FORM_ID', 'doctype:10'])
expect(StatsD).not_to have_received(:increment).with('saved_claim.pdf.overflow', tags:)
end
end
end
context 'after destroy' do
it 'increments the saved_claim.destroy metric' do
saved_claim.save!
allow(StatsD).to receive(:increment)
saved_claim.destroy
expect(StatsD).to have_received(:increment).with('saved_claim.destroy', tags:)
end
end
end
describe '#process_attachments!' do
let(:confirmation_code) { SecureRandom.uuid }
let(:form_data) { { some_key: [{ confirmationCode: confirmation_code }] }.to_json }
it 'processes attachments associated with the claim' do
attachment = create(:persistent_attachment, guid: confirmation_code, saved_claim:)
saved_claim.process_attachments!
expect(attachment.reload.saved_claim_id).to eq(saved_claim.id)
expect(Lighthouse::SubmitBenefitsIntakeClaim).to have_enqueued_sidekiq_job(saved_claim.id)
end
end
describe '#confirmation_number' do
it 'returns the claim GUID' do
expect(saved_claim.confirmation_number).to eq(saved_claim.guid)
end
end
describe '#submitted_at' do
it 'returns the created_at' do
expect(saved_claim.submitted_at).to eq(saved_claim.created_at)
end
end
describe '#to_pdf' do
it 'calls PdfFill::Filler.fill_form' do
expect(PdfFill::Filler).to receive(:fill_form).with(saved_claim, nil)
saved_claim.to_pdf
end
end
describe '#update_form' do
it 'updates the form with new data' do
saved_claim.update_form('new_key', 'new_value')
expect(saved_claim.parsed_form['new_key']).to eq('new_value')
end
end
describe '#business_line' do
it 'returns empty string' do
expect(saved_claim.business_line).to eq('')
end
end
describe '#insert_notification' do
it 'creates a new ClaimVANotification record' do
saved_claim.save!
expect do
saved_claim.insert_notification(1)
end.to change(saved_claim.claim_va_notifications, :count).by(1)
end
end
describe '#va_notification?' do
let(:email_template_id) { 0 }
let!(:notification) do
ClaimVANotification.create(
saved_claim:,
email_template_id:,
form_type: saved_claim.form_id,
email_sent: false
)
end
it 'returns the notification if it exists' do
expect(saved_claim.va_notification?(email_template_id)).to eq(notification)
end
it 'returns nil if the notification does not exist' do
expect(saved_claim.va_notification?('non_existent_template')).to be_nil
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents_v2/child_stopped_attending_school_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependentsV2::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' => 'Y'
}
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_v2/veteran_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependentsV2::Veteran do
let(:address) { { addrs_one_txt: '123 mainstreet', cntry_nm: 'USA', vnp_ptcpnt_addrs_id: '116343' } }
let(:all_flows_payload_v2) { build(:form686c_674_v2) }
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_v2) do
{
'first' => 'WESLEY',
'last' => 'FORD',
'phone_number' => '5555555555',
'email_address' => 'test@test.com',
'country' => 'USA',
'street' => '123 fake street',
'street2' => 'test2',
'street3' => 'test3',
'city' => 'portland',
'state' => 'ME',
'postal_code' => '04102',
'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_v2)).to include(formatted_params_result_v2)
end
it 'formats params given a veteran that is married' do
formatted_params_result_v2['martl_status_type_cd'] = 'Married'
all_flows_payload_v2['dependents_application']['does_live_with_spouse']['spouse_does_live_with_veteran'] = true
expect(vet.formatted_params(all_flows_payload_v2)).to include(formatted_params_result_v2)
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.