Learning Rspec, working with just Ruby, not Rails. I have a script that works as expected from the command line, but I can't get the test to pass.
The relevant code:
class Tree
attr_accessor :height, :age, :apples, :alive
def initialize
@height = 2
@age = 0
@apples = false
@alive = true
end
def age!
@age += 1
end
And the spec:
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
And the error:
1) Tree #age! ages the tree object one year per call
Failure/Error: expect(@age).to eq(10)
expected: 10
got: nil
(compared using ==)
I think that is all the relevant code, please let me know if I'm missing something in the code I posted. From what I can tell the error comes from scoping within rspec, and the @age variable is not being passed into the rspec test in a way that I think it should, thus being nil when trying to call the function within the test.
@age
is a variable within each of your Tree
objects. You're right that this is a scoping 'problem', more a scoping feature - your test has no variable named @age
.
What it does have is a variable called @tree
. That Tree
has a property called age
. This should work, let me know if it doesn't:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With