Database Cleaner not working in minitest rails

后端 未结 5 620
慢半拍i
慢半拍i 2021-01-02 14:48

My Minitest controller tests are working fine if I run them alone using rake minitest:controllers but when I run rake minitest:all then I get valid

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 15:11

    This is why I like Minitest; no fancy DSL to block thinking about how to use Ruby properly.

    My setup is as follows:

    In test_helper.rb

    class MyTest < Minitest::Test
      def setup
        DatabaseCleaner.start
      end
    
      def teardown
        DatabaseCleaner.clean
      end
    end
    

    Then I just subclass this in any test that need database cleaning. Note the call super first cleans the db before any subclass-specific setup. The same call to super would need to be included in any subclass teardown method, but this can usually be omitted entirely.

    class FooTest < MyTest
      def setup
        super
        @foo = Foo.new(bar: 'whatever')
      end
    
      def test_save
        @foo.save
        assert_equal 1, Foo.count
      end
    end
    

    If I need to subclass MyTest further (e.g. for integration tests) I include its own setup & teardown methods with calls to super so it goes right up the inheritance tree.

提交回复
热议问题