Skip to content

Commit

Permalink
avoid creating duplicate problems
Browse files Browse the repository at this point in the history
resolves #2811
  • Loading branch information
Floppy committed Sep 27, 2024
1 parent 0e86bc4 commit b417674
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
10 changes: 5 additions & 5 deletions app/models/problem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ class Problem < ApplicationRecord
no_tags: :silent
)

def self.create_or_clear(problematic, cat, present, options = {})
if present
problematic.problems.create(options.merge(category: cat))
def self.create_or_clear(problematic, category, should_exist, options = {})
if should_exist
problematic.problems.find_or_create_by(options.merge(category: category))
else
problematic.problems.where(category: cat).destroy_all
problematic.problems.where(category: category).destroy_all
end
present
should_exist
end

def self.ransackable_attributes(auth_object = nil)
Expand Down
32 changes: 32 additions & 0 deletions spec/models/problem_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,36 @@
expect(described_class.count).to eq(1)
end
end

context "when updating problem state" do
let(:model) { create(:model, license: nil) }

it "creates a problem that should exist but doesn't" do
expect {
described_class.create_or_clear model, :no_license, model.license.blank?
}.to change(described_class, :count).from(0).to(1)
end

it "removes a problem that shouldn't exist but does" do
described_class.create_or_clear model, :no_license, model.license.blank?
model.update!(license: "CC-BY-4.0")
expect {
described_class.create_or_clear model, :no_license, model.license.blank?
}.to change(described_class, :count).from(1).to(0)
end

it "does nothing with a problem that shouldn't exist and doesn't" do
model.update!(license: "CC-BY-4.0")
expect {
described_class.create_or_clear model, :no_license, model.license.blank?
}.not_to change(described_class, :count)
end

it "does nothing with a problem that should exist and does" do
described_class.create_or_clear model, :no_license, model.license.blank?
expect {
described_class.create_or_clear model, :no_license, model.license.blank?
}.not_to change(described_class, :count)
end
end
end

0 comments on commit b417674

Please sign in to comment.