Ruby 意外的rspec行为
学习Rspec,只使用Ruby,不使用Rails。我有一个脚本,可以从命令行按预期工作,但我无法通过测试 有关守则:Ruby 意外的rspec行为,ruby,rspec,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 en
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测试中,因此在尝试调用测试中的函数时为零
@age
是每个树
对象中的一个变量。你是对的,这是一个范围界定“问题”,更多的是一个范围界定功能-你的测试没有名为@age
的变量
它有一个名为@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
描述“树”是什么
以前:每个人都做
@tree=tree.new
结束
描述“年龄!”做什么
它“每次调用一年使树对象老化”do
10.times{@tree.age!}
expect(@tree.age)。对于等式(10)#谢谢,按预期工作。我的问题是,由于该方法与rspec'expect'Ruby在同一个块中调用,因此它会神奇地理解我的问题。几个月前,我刚刚意识到我在不同的环境中遇到了同样的问题——下次我会记得的。