Skip to content

Commit bfa1867

Browse files
authored
Merge pull request #2828 from govuk-forms/fix-stale-condition-check
Fix stale_conditions same answer value conditions
2 parents 7f862dc + 0921569 commit bfa1867

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

app/services/routes/sync_service.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def update_or_create_conditions
3030
condition.assign_attributes(
3131
route.condition_attributes,
3232
)
33+
3334
condition.save!
3435
end
3536
end
@@ -40,10 +41,14 @@ def destroy_stale_conditions
4041
# If there are no routes marked as default, there's nothing to destroy.
4142
return if default_routes.none?
4243

44+
stale_route_pairs = default_routes.map do |route|
45+
[route.page_id, route.answer_value.presence]
46+
end
47+
4348
stale_conditions = form.conditions.where(
44-
routing_page_id: default_routes.map(&:page_id),
45-
answer_value: default_routes.map { |r| r.answer_value.presence },
49+
%i[routing_page_id answer_value] => stale_route_pairs,
4650
)
51+
4752
stale_conditions.destroy_all
4853
end
4954
end

spec/services/routes/sync_service_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,17 +71,32 @@
7171
create(:condition, routing_page_id: pages.first.id, answer_value: "Yes", goto_page_id: pages.second.id)
7272
end
7373

74+
# Create a condition that shouldn't be removed
75+
let!(:healthy_condition) do
76+
create(:condition, routing_page_id: pages.second.id, answer_value: "Yes", goto_page_id: pages.third.id)
77+
end
78+
7479
# Provide a route that matches the stale condition's key, but is now a "default" route.
7580
let(:routes) do
7681
[
82+
# Route for the first page, which is default so conditions are removed
7783
build(:route_input, :default, page: pages.first, answer_value: "Yes"),
84+
# Two routes for the second page, which should not be removed
85+
build(:route_input, page: pages.second, goto: pages.third.id, answer_value: "Yes"),
86+
# This is default but has no conditions to remove
87+
build(:route_input, :default, page: pages.second, answer_value: "No"),
7888
]
7989
end
8090

8191
it "destroys the condition that is now a default route" do
8292
expect { service.sync_conditions_from_routes }.to change(Condition, :count).by(-1)
8393
expect(Condition.exists?(stale_condition.id)).to be false
8494
end
95+
96+
it "does not destroy other page's conditions with the same answer value" do
97+
service.sync_conditions_from_routes
98+
expect(Condition.exists?(healthy_condition.id)).to be true
99+
end
85100
end
86101

87102
context "with an answer_value of an empty string" do

0 commit comments

Comments
 (0)