当在不同的单元测试中访问时,为什么此实例变量为nil?

时间:2010-07-15 17:48:21

标签: ruby unit-testing testunit

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

2 个答案:

答案 0 :(得分:2)

差异似乎是你在第二次测试中没有调用@ thing.set_stuff。

答案 1 :(得分:1)

我不像RSpec那样熟悉Test :: Unit,但我相信每次运行测试时都会调用setup()方法。所以一个@thing将被另一个覆盖。

此外,我发现您无法承担执行测试用例的特定订单;通常(也许一直都是?)测试从最后到第一次运行,就像在这种情况下的情况一样。