saasbook

demeter_example.rb

Aug 15th, 2013
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.94 KB | None | 0 0
  1. # This example is adapted from Dan Manges's blog, dcmanges.com
  2. class Wallet ; attr_accessor :credit_balance ; end
  3. class Moviegoer
  4.   attr_accessor :wallet
  5.   def initialize
  6.     # ...setup wallet attribute with correct credit balance
  7.   end
  8. end
  9. class MovieTheater
  10.   def collect_money(moviegoer, amount)
  11.     # VIOLATION OF DEMETER (see text)
  12.     if moviegoer.wallet.credit_balance < amount
  13.       raise InsufficientFundsError
  14.     else
  15.       moviegoer.wallet.credit_balance -= due_amount
  16.       @collected_amount += due_amount
  17.     end
  18.   end
  19. end
  20. # Imagine testing the above code:
  21. describe MovieTheater do
  22.   describe "collecting money" do
  23.     it "should raise error if moviegoer can't pay" do
  24.       # "Mock trainwreck" is a warning of a Demeter violation
  25.       wallet = mock('wallet', :credit_balance => 5.00)
  26.       moviegoer = mock('moviegoer', :wallet => wallet)
  27.       lambda { @theater.collect_money(moviegoer, 10.00) }.
  28.         should raise_error(...)
  29.     end
  30.   end
  31. end
Add Comment
Please, Sign In to add comment