ExpectationNotMetError,方法返回nil

时间:2014-10-13 04:15:21

标签: ruby attr-accessor

我正在进行在线练习。我被要求创建一个InterestCalculator类,它在初始化时需要四个参数,并定义了两个函数amountstatement。我必须在整个班级中使用self方法。实例变量只能在initialize函数中直接访问,amount只能在一个地方计算。

以下是规格:

describe InterestCalculator do
  before { @calc = InterestCalculator.new(500, 0.05, 4, 5) }

  describe "#amount" do
    it "calculates correctly" do
      expect( @calc.amount ).to eq(610.1)
    end
  end

  describe "#statement" do
    it "calls amount" do
      @calc.stub(:amount).and_return(100)
      expect( @calc.statement ).to eq("After 4 years I'll have 100 dollars!")
    end
  end
end

这是我的代码:

class InterestCalculator
  attr_accessor :amount, :statement

  def initialize(principal, rate, years, times_compounded)
    @principal = principal
    @rate = rate
    @years = years
    @times_compounded = times_compounded
  end
  def self.amount
    amount = principal * (1 + rate / times_compounded) ** (times_compounded * years)
  end
  def self.statement
    statement = "After #{years} years i'll have #{amount} dollars"
  end
end

我一直收到以下错误,不知道原因:

RSpec::Expectations::ExpectationNotMetError

expected: 610.1
     got: nil

RSpec::Expectations::ExpectationNotMetError

expected: "After 4 years I'll have 100 dollars!"
     got: nil

2 个答案:

答案 0 :(得分:2)

如果您打算将amountstatement作为实例方法,请将代码更改为

def amount
  @amount ||= @principal * (1 + @rate / @times_compounded) ** (@times_compounded * @years)
end

def statement
  @statement ||= "After #{@years} years i'll have #{amount} dollars"
end

这是因为

def self.my_method
  # method body
end

创建一个类方法。此外,如果您希望amountstatement为只读,请将attr_accessor更改为attr_reader

答案 1 :(得分:-1)

让它像这样工作:

class InterestCalculator
  attr_accessor :amount, :statement, :years

  def initialize(principal, rate, years, times_compounded)
    @principal = principal
    @rate = rate
    @years = years
    @times_compounded = times_compounded
    self.amount = principal * (1 + rate / times_compounded) ** (times_compounded * years)
    self.amount = amount.round(1)
  end

  def statement
    statement = "After #{years} years I'll have #{amount} dollars!"
  end

end

谢谢!