Skip to content

Commit

Permalink
fix: handle race conditions when creating a pacticipant
Browse files Browse the repository at this point in the history
  • Loading branch information
bethesque committed Nov 15, 2018
1 parent f6cfb19 commit b379967
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/pact_broker/pacticipants/repository.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,13 @@ def find_by_name_or_create name
end

def create args
PactBroker::Domain::Pacticipant.new(name: args[:name], repository_url: args[:repository_url]).save(raise_on_save_failure: true)
id = PactBroker::Domain::Pacticipant.dataset.insert_ignore.insert(
name: args[:name],
repository_url: args[:repository_url],
created_at: Sequel.datetime_class.now,
updated_at: Sequel.datetime_class.now
)
PactBroker::Domain::Pacticipant.find(id: id)
end

def pacticipant_names
Expand Down
33 changes: 33 additions & 0 deletions spec/lib/pact_broker/pacticipants/repository_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,39 @@
module PactBroker
module Pacticipants
describe Repository do
describe "#create" do
let(:repository) { Repository.new }

subject { repository.create(name: "Foo") }

context "when the pacticipant does not already exist" do
before do
TestDataBuilder.new.create_pacticipant("Bar")
end

subject { repository.create(name: "Foo") }

it "returns the new pacticipant" do
expect(subject).to be_a(PactBroker::Domain::Pacticipant)
expect(subject.name).to eq "Foo"
end
end

context "when a race condition occurs and the pacticipant was already created by another request" do
before do
TestDataBuilder.new.create_pacticipant("Foo")
end

it "does not raise an error" do
subject
end

it "returns the existing pacticipant" do
expect(subject).to be_a(PactBroker::Domain::Pacticipant)
expect(subject.name).to eq "Foo"
end
end
end

describe "#find" do
before do
Expand Down

0 comments on commit b379967

Please sign in to comment.