5
学习Rspec,只使用Ruby而不使用Rails。我有一个从命令行按预期工作的脚本,但我无法通过测试。意外的rspec行为
相关的代码:
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测试,因此在尝试调用测试内的函数时为零。
谢谢,按预期工作。我的问题在于,由于该方法在rspec'expect'的同一个块中被调用,Ruby会奇迹般地理解我在问什么。我刚刚意识到我在几个月前在不同的环境中遇到了同样的问题 - 我将在下一次回忆。 –