discourse-solved/spec/models/copy_solved_topic_custom_field_spec.rb
Natalie Tay 1805184cde
FIX: Multiple topics may have the same post as its solution (#348)
We are seeing some errors when migrating and adding indexes on `answer_post_id`.

```
#<StandardError:"An error has occurred, all later migrations canceled:\n\nPG::UniqueViolation: ERROR:  could not create unique index \"index_discourse_solved_solved_topics_on_answer_post_id\"\nDETAIL:  Key (answer_post_id)=(13006) is duplicated.\n">
```

This PR modifies the earlier migration, and also adds one before the addition of indexes to remove duplicates.
2025-03-26 22:21:32 +08:00

43 lines
1.3 KiB
Ruby

# frozen_string_literal: true
require_relative "../../db/migrate/20250318024953_copy_solved_topic_custom_field_to_discourse_solved_solved_topics"
RSpec.describe CopySolvedTopicCustomFieldToDiscourseSolvedSolvedTopics, type: :migration do
let(:migration) { described_class.new }
describe "handling duplicates" do
it "ensures only unique topic_id and answer_post_id are inserted" do
topic = Fabricate(:topic)
topic1 = Fabricate(:topic)
post1 = Fabricate(:post, topic: topic)
TopicCustomField.create!(
topic_id: topic.id,
name: "accepted_answer_post_id",
value: post1.id.to_s,
)
# explicit duplicate
TopicCustomField.create!(
topic_id: topic1.id,
name: "accepted_answer_post_id",
value: post1.id.to_s,
)
second_topic = Fabricate(:topic)
post2 = Fabricate(:post, topic: second_topic)
TopicCustomField.create!(
topic_id: second_topic.id,
name: "accepted_answer_post_id",
value: post2.id.to_s,
)
migration.up
expected_count = DiscourseSolved::SolvedTopic.count
expect(expected_count).to eq(2)
expect(DiscourseSolved::SolvedTopic.where(topic_id: topic.id).count).to eq(1)
expect(DiscourseSolved::SolvedTopic.where(answer_post_id: post1.id).count).to eq(1)
end
end
end