Ruby + Rspec + OOP:类使用的双重/存根对象,还是实例化实际类?

时间:2013-11-28 19:01:52

标签: ruby oop rspec

我是一名铁路开发者,我正在尝试提升我的OOP游戏。最近我一直在观看Sandi Metz的演讲并阅读Ruby中的Design Patterns。

在对象中何时使用对象(这会导致依赖性?)似乎有一个很好的界限。我有一个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

我的购买课程:

{{1}}

这更像是我的rspec测试还是我的设计?

1 个答案:

答案 0 :(得分: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超类的initialize方法将stockbank_account存储到实例变量中。