Unexpected rspec behavior

Rspec training that works only with Ruby, not Rails. I have a script that works as expected from the command line, but I can not pass the test.

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 specification:

 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 this is all relevant code, please let me know if I missed something in the code that I posted. From what I can tell, the error comes from the scope inside rspec, and the @age variable is not passed to the rspec test as I assume it should be zero when trying to call a function in the test.

+5
source share
1 answer

@age is a variable in each of your Tree objects. You are right that this is a problem with determining the scope, a more detailed function - your test does not have a variable named @age .

What he has is a variable called @tree . This Tree property has an age property. This should work, let me know if it is not:

 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 
+5
source

Source: https://habr.com/ru/post/1244250/


All Articles