如何让这个测试通过,我有点困惑

时间:2017-12-01 03:39:35

标签: ruby

这是我的钱类

class Money
  def initialize
    @amount = 0
  end

  def amount
    @amount
  end

  def earn(this_many)
    @amount += this_many
  end

  def spend(this_many)
    @amount -= this_many
  end

end

我的测试失败

  def test_cant_spend_money_that_you_dont_have
    money = Money.new
    money.earn(75)
    money.spend(75)
    assert_equal "You can't spend what you don't have", money.spend(12)
    assert_equal 0, money.amount
  end

我不确定如何修改金额方法以使测试通过...任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果帐户没有足够的资金支出,您应该提出错误。

class Money
  class InsufficientFunds < StandardError; end

  attr_accessor :amount

  def initialize
    self.amount = 0
  end

  def earn(this_many)
    self.amount += this_many
  end

  def spend(this_many)
    raise InsufficientFunds, "You can't spend what you don't have" if amount < this_many
    self.amount -= this_many
  end

end

你的测试用例应该是

def test_cant_spend_money_that_you_dont_have
  money = Money.new
  money.earn(75)
  money.spend(75)
  assert_raise Money::InsufficientFunds, "You can't spend what you don't have" do
    money.spend(12)
  end
  assert_equal 0, money.amount
end

答案 1 :(得分:0)

我认为你需要改变

assert_equal "You can't spend what you don't have", money.spend(12)

money.spend(12)
assert money.amount > 0, "You can't spend what you don't have"