意外的rspec行为

时间:2016-03-01 20:06:29

标签: ruby rspec

学习Rspec,只使用Ruby,而不是Rails。我有一个脚本可以从命令行按预期工作,但我无法通过测试。

相关代码:

  class Tree    
  attr_accessor :height, :age, :apples, :alive

  def initialize
    @height = 2
    @age = 0
    @apples = false
    @alive = true
  end      

  def age!
    @age += 1
  end

规范:

describe "Tree" do

  before :each do
    @tree = Tree.new
  end

  describe "#age!" do
    it "ages the tree object one year per call" do
      10.times { @tree.age! }
      expect(@age).to eq(10)
    end
  end
end

错误:

  1) Tree #age! ages the tree object one year per call
     Failure/Error: expect(@age).to eq(10)

       expected: 10
            got: nil

       (compared using ==)

我认为这是所有相关的代码,如果我在发布的代码中遗漏了某些内容,请告诉我。从我可以看出错误来自rspec中的范围,并且@age变量没有以我认为应该的方式传递到rspec测试,因此在尝试调用测试中的函数时是nil。

1 个答案:

答案 0 :(得分:5)

@age是每个Tree个对象中的变量。你是对的,这是一个范围问题'更多的范围界定功能 - 你的测试没有名为@age的变量。

它具有的是一个名为@tree的变量。 Tree有一个名为age的属性。这应该有用,如果它没有,请告诉我:

describe "Tree" do

  before :each do
    @tree = Tree.new
  end

  describe "#age!" do
    it "ages the tree object one year per call" do
      10.times { @tree.age! }
      expect(@tree.age).to eq(10) # <-- Change @age to @tree.age
    end
  end
end