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
views:
27answers:
2
+2
A:
The difference looks to be that you're not calling @thing.set_stuff in the second test.
Jacob Ewald
2010-07-15 17:58:50
So the state of my object in `setup` doesn't persist through test methods?
rpflo
2010-07-15 18:11:51
Correct. Your setup method will be called before each and every test method in the test fixture. So to list all of the calls while running these test cases would be1. setup2. test_set_stuff3. teardown4. setup5. test_foo_in_other_test6. teardownBoth setup and teardown are optional. You don't need to have those and in your case you've only defined setup, which is totally fine.
Jacob Ewald
2010-07-15 18:30:30
I eventually figure that out, thanks for the explanation.
rpflo
2010-07-16 05:13:09
+1
A:
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.
Eric W.
2010-07-16 03:06:41