In Ruby's Test::Unit::TestCase, how do I override the initialize method?

前端 未结 10 1849
再見小時候
再見小時候 2020-12-07 14:54

I\'m struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby\'s framework, I must instead write:

class M         


        
10条回答
  •  旧时难觅i
    2020-12-07 15:20

    +1 for the RSpec answer above by @orion-edwards. I would have commented on his answer, but I don't have enough reputation yet to comment on answers.

    I use test/unit and RSpec a lot and I have to say ... the code that everyone has been posting is missing a very important feature of before(:all) which is: @instance variable support.

    In RSpec, you can do:

    describe 'Whatever' do
      before :all do
        @foo = 'foo'
      end
    
      # This will pass
      it 'first' do
        assert_equal 'foo', @foo
        @foo = 'different'
        assert_equal 'different', @foo
      end
    
      # This will pass, even though the previous test changed the 
      # value of @foo.  This is because RSpec stores the values of 
      # all instance variables created by before(:all) and copies 
      # them into your test's scope before each test runs.
      it 'second' do
        assert_equal 'foo', @foo
        @foo = 'different'
        assert_equal 'different', @foo
      end
    end
    

    The implementations of #startup and #shutdown above all focus on making sure that these methods only get called once for the entire TestCase class, but any instance variables used in these methods would be lost!

    RSpec runs its before(:all) in its own instance of Object and all of the local variables are copied before each test is run.

    To access any variables that are created during a global #startup method, you would need to either:

    • copy all of the instance variables created by #startup, like RSpec does
    • define your variables in #startup into a scope that you can access from your test methods, eg. @@class_variables or create class-level attr_accessors that provide access to the @instance_variables that you create inside of def self.startup

    Just my $0.02!

提交回复
热议问题