Chantal
Chantal

Reputation: 33

How to make this test pass, I'm a bit confused

this is my money class

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

my failing test

  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

I'm not sure how to modify the amount method to make the test pass... any help will be appreciated.

Upvotes: 0

Views: 76

Answers (2)

Aetherus
Aetherus

Reputation: 8898

You should raise errors when the account doesn't have enough money to spend.

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

And your test case should be

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

Upvotes: 2

Inacio Dsilva
Inacio Dsilva

Reputation: 1

I think you need to change

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

to

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

Upvotes: 0

Related Questions