2013-11-28 89 views
0

我是一名rails開發人員,我正在嘗試開發我的OOP遊戲。最近我一直在觀看Sandi Metz的演講,並閱讀Ruby中的Design Patterns。Ruby + Rspec + OOP:類使用的雙/對象對象,或實例化實際類?

似乎與何時使用對象內的對象細線(這將導致依賴?)。我有一個Purchase類需要BankAccount實例從取錢。我的測試失敗了,因爲它將.balance方法存儲爲bank_account以返回固定值。這似乎是我在這個測試中扼殺了一些東西,這似乎是對我的警告。但Purchase確實需要股市和銀行賬戶,所以我不知道如果我的設計太耦合,或者如果這是不可避免的:

describe "#execute" do 
     it 'withdraws money from the bank account' do 
      stock = double('Stock') 
      stock.stub(:price).and_return(1) 
      bank_account = double('Bank Account') 
      bank_account.stub(:balance).and_return(2000.00) 
      bank_account.stub(:withdraw).and_return(bank_account.balance - (stock.price * 100)) 
      purchase = Purchase.new(stock, 100, bank_account) 
      purchase.execute 
      purchase.bank_account.balance.should eq(bank_account.balance - (stock.price * 100)) 
     end 
    end 

我的購買等級:

class Purchase < Transaction 
     attr_reader :shares 

     def initialize(stock, shares, bank_account) 
      super(stock, bank_account) 
      @shares = shares 
     end 

     def execute #<-- trying to test this 
      @bank_account.withdraw(@stock.price * @shares) 
     end 

    end 

這是更我的rspec測試或我的設計的問題?

回答

1

如果你只是寫一個單元測試,然後你想/需要做的是確保所測試的軟件使得它需要向它的合作對象的調用。因此,以下就足夠了:

describe '#execute' do 
    it 'withdraws money from the bank account' do 
    stock_price = 1 
    stock = double('stock', price: stock_price) 
    shares = 100 
    bank_account = double('bank_account') 
    expect(bank_account).to receive(:withdraw).with(stock_price*shares) 
    Purchase.new(stock, shares, bank_account).execute 
    end 
end 

該測試假定Transaction超類存儲stockbank_account到實例變量的初始化方法。