Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected rspec behavior

Tags:

ruby

rspec

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.

like image 245
Nate Anderson Avatar asked Mar 01 '16 20:03

Nate Anderson


1 Answers

@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
like image 168
Undo Avatar answered Oct 14 '22 06:10

Undo