Skip to content
Browse files

Sanity checks for group mismatch in adding debt

  • Loading branch information...
1 parent 526704f commit e9fcc339a1f36949aadc9bf00c2e64ff1886121a Michal Bugno committed May 17, 2012
Showing with 32 additions and 0 deletions.
  1. +12 −0 lib/debt_adder.rb
  2. +20 −0 spec/unit/debt_adder_spec.rb
View
12 lib/debt_adder.rb
@@ -1,9 +1,17 @@
class DebtAdder
+ class Error < Exception
+ end
+
def initialize(giver, takers, group, amount)
@giver = giver
@takers = takers
@group = group
@amount = amount
+
+ raise Error.new("Group mismatch") unless membership?(@giver, @group)
+ @takers.each do |taker|
+ raise Error.new("Group mismatch") unless membership?(taker, @group)
+ end
end
def add_debt
@@ -37,4 +45,8 @@ def charge_takers
def change_balance(person, amount)
DebtElement.create!(:debt_id => debt.id, :person_id => person.id, :amount => amount)
end
+
+ def membership?(person, group)
+ !person.group_memberships.where(:group_id => group.id).empty?
+ end
end
View
20 spec/unit/debt_adder_spec.rb
@@ -27,6 +27,7 @@
it "splits debt between users" do
taker2 = FactoryGirl.create :person
+ FactoryGirl.create :group_membership, :group_id => group.id, :person_id => taker2.id
adder = DebtAdder.new(giver, [taker, taker2], group, 50)
adder.add_debt
@@ -42,6 +43,7 @@
it "divides reminder between users so that total amount sums" do
taker2 = FactoryGirl.create :person
+ FactoryGirl.create :group_membership, :group_id => group.id, :person_id => taker2.id
adder = DebtAdder.new(giver, [taker, taker2], group, 49)
adder.add_debt
@@ -64,4 +66,22 @@
elements = DebtElement.where(:debt_id => debt.id, :person_id => [taker.id]).all
elements.map(&:amount).sum.should == -100
end
+
+ describe "#initialize" do
+ let(:group2) { FactoryGirl.create :group }
+
+ it "raises if giver doesn't belong to group" do
+ membership = GroupMembership.where(:person_id => giver.id).first
+ membership.update_attributes(:group_id => group2.id)
+
+ lambda { DebtAdder.new(giver, [taker], group, 10) }.should raise_error(DebtAdder::Error)
+ end
+
+ it "raises if taker doesn't belong to group" do
+ membership = GroupMembership.where(:person_id => taker.id).first
+ membership.update_attributes(:group_id => group2.id)
+
+ lambda { DebtAdder.new(giver, [taker], group, 10) }.should raise_error(DebtAdder::Error)
+ end
+ end
end

0 comments on commit e9fcc33

Please sign in to comment.
Something went wrong with that request. Please try again.