Ryan Florence
Ryan Florence

Reputation: 13483

Why is this instance variable nil when accessed in a different unit test?

require 'rubygems'
require 'test/unit'

class Thing
  attr_accessor :foo

  def set_stuff
    @foo = 'bar'
  end
end

class ThingTest < Test::Unit::TestCase
  def setup
    @thing = Thing.new
  end

  def test_set_stuff
    @thing.set_stuff
    assert 'bar' == @thing.foo
  end

  def test_foo_in_other_test
    puts @thing.foo
    assert 'bar' == @thing.foo
  end
end


# Loaded suite testing
# Started
# nil
# F.
# Finished in 0.00439 seconds.
#
#   1) Failure:
# test_foo_in_other_test(ThingTest) [testing.rb:26]:
# <false> is not true.
#
# 2 tests, 2 assertions, 1 failures, 0 errors

Upvotes: 2

Views: 542

Answers (2)

Eric Walker
Eric Walker

Reputation: 7591

I'm not as familiar with Test::Unit as RSpec, but I believe the setup() method will be called each time a test is run. So one @thing will be overwritten by another.

In addition, I've found that you can't assume a particular order for the execution of test cases; often (perhaps all the time?) the tests are run from last to first, as seems to be the case in this instance.

Upvotes: 1

Jacob Ewald
Jacob Ewald

Reputation: 2178

The difference looks to be that you're not calling @thing.set_stuff in the second test.

Upvotes: 2

Related Questions