学习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。
答案 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