Skip to content

Commit

Permalink
Fix error handling when fetching constituencies
Browse files Browse the repository at this point in the history
Don't reset the retried flag inside the block being retried.
  • Loading branch information
pixeltrix committed Jul 6, 2024
1 parent c4683ab commit 817b077
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 4 additions & 3 deletions app/jobs/fetch_constituencies_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ class FetchConstituenciesJob < ApplicationJob

def perform
constituencies.each do |external_id, name, ons_code, start_date, end_date|
begin
retried = false
retried = false

begin
Constituency.for(external_id) do |constituency|
constituency.name = name
constituency.ons_code = ons_code
Expand All @@ -31,8 +31,9 @@ def perform
constituency.save!
end
rescue ActiveRecord::RecordNotUnique => e
retry unless retried
next if retried
retried = true
retry
end
end
end
Expand Down
15 changes: 15 additions & 0 deletions spec/jobs/fetch_constituencies_job_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,21 @@ def odata_response(status, body = nil, &block)
stub_constituency_api.to_return(odata_response(:ok, "constituencies"))
end

context "when a record is duplicated" do
let(:constituency) { instance_spy(Constituency) }

before do
allow(Constituency).to receive(:find_or_initialize_by).and_call_original
allow(Constituency).to receive(:find_or_initialize_by).with(external_id: "3320").and_return(constituency)
allow(constituency).to receive(:save!).and_raise(ActiveRecord::RecordNotUnique)
end

it "retries twice before skipping" do
described_class.perform_now
expect(constituency).to have_received(:save!).twice
end
end

context "when a record fails to save" do
let!(:constituency) { FactoryBot.create(:constituency, :bethnal_green_and_bow) }
let(:exception) { ActiveRecord::RecordInvalid.new(constituency) }
Expand Down

0 comments on commit 817b077

Please sign in to comment.