From: Morton Goldberg Date: 2006-08-31T04:40:28+09:00 Subject: Re: [QUIZ] DayRange (#92) Test::Unit gotcha Thanks for trying to help, but if I understand how setup functions, your modification defeats my requirement that the test objects be created once and once only. As I understand it, setup will run before EACH test and the test objects will be created over and over again, even for test_bad_args where they are not needed at all. Renaming test_valid_args to test_args is not only simpler, it meets the requirement of parsimony of test objects. Regards, Morton On Aug 30, 2006, at 1:27 PM, James Edward Gray II wrote: > On Aug 30, 2006, at 11:55 AM, Morton Goldberg wrote: > >> Could you post an example showing how setup and teardown could be >> used to avoid the trap I fell into? > > Here's my modification to your tests to get them working with setup(): > > class TestDayRange < Test::Unit::TestCase > > # All these produce @days == [1..7]. > ONE_RANGE = [ > %w[mon tue wed thu fri sat sun], > %w[monDay tuesday Wednesday Thursday friDAY saturday SUNDAY], > %w[mon-fri sat-sun], > %w[4-7 1-3], > (1..7).to_a.reverse, > [4, 7, 6, 5, 4, 1, 2, 1, 2, 3, 3, 7, 6, 5], > ] > > # Both these produce @days == [1..3, 5..7]. > TWO_RANGES = [ > %w[mon-mon tue-tue wed-wed fri-sun], > [1, 2, 'mon-wed', 'friday', 6, 7] > ] > > INVALID_ARGS = [ > [1, 2, 'foo'], > %w[foo-bar], > %w[sat-mon], > (0..7).to_a.reverse, > (1..8).to_a > ] > > def setup > assert_nothing_raised(ArgumentError) do > @one_range = ONE_RANGE.map { |args| DayRange.new(*args) } > end > assert_nothing_raised(ArgumentError) do > @two_ranges = TWO_RANGES.map { |args| DayRange.new(*args) } > end > end > > def test_valid_args > @one_range.each do |obj| > assert_expected_days([1..7], obj) > end > @two_ranges.each do |obj| > assert_expected_days([1..3, 5..7], obj) > end > end > > def test_bad_args > INVALID_ARGS.each do |args| > assert_raise(ArgumentError) { DayRange.new(*args) } > end > end > > def test_to_s > @one_range.each do |obj| > assert_equal('Mon-Sun', obj.to_s) > end > @two_ranges.each do |obj| > assert_equal('Mon-Wed, Fri-Sun', obj.to_s) > end > end > > def test_to_a > @one_range.each do |obj| > assert_equal((1..7).to_a, obj.to_a) > end > @two_ranges.each do |obj| > assert_equal([1, 2, 3, 5, 6, 7], obj.to_a) > end > end > > private > > def assert_expected_days(expected, day_range) > assert_equal(expected, day_range.instance_variable_get(:@days)) > end > > end > > James Edward Gray II >