【问题标题】:Ruby + Rspec + OOP: Doubles/stubbing objects that the class uses, or instantiating actual class?Ruby + Rspec + OOP:类使用的双打/存根对象,或实例化实际类?
【发布时间】: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 测试还是我的设计?

【问题讨论】:

    标签: ruby oop 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 存储到实例变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 2014-07-06
      相关资源
      最近更新 更多