【发布时间】:2013-12-14 21:49:39
【问题描述】:
我是一名 Rails 开发人员,我正在努力提升我的 OOP 游戏。最近我一直在看 Sandi Metz 的演讲和阅读 Ruby 中的设计模式。
似乎在何时使用对象中的对象(这会导致依赖关系?)方面存在细微差别。我有一个Purchase 类,它需要一个BankAccount 实例来提取资金。我的测试失败了,因为我为bank_account 存根了.balance 方法以返回一个固定值。似乎我在这个测试中存了很多东西,这对我来说似乎是一个警告。但是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 测试还是我的设计?
【问题讨论】: