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 validation failed error. It is because email is already used in model tests. I used DatabaseCleaner to clean the database but unable to clean database.
My code for database cleaner:
require "database_cleaner"
DatabaseCleaner.strategy = :transaction
class MiniTest::Rails::ActionController::TestCase
include Devise::TestHelpers
def setup
DatabaseCleaner.start
end
def teardown
DatabaseCleaner.clean
end
You can DRY up that repetition with this
This example subclasses the spec runner, but you can pick your test environment of choice.
Short answer:
Long answer:
before/after or setup/teardown in minitest are NOT hooks as in rspec, therefore you can't have multiple before/after or setup/teardown in minitest, since what they do is just redefining the method.
To solve this issue, you can use
minitest-around
, which adds support for multiplebefore
/after
orsetup
/teardown
andaround
, simply add the gem to your test group:For setting up the database_cleaner, you can have it as you want, following is an example of the setup:
And in your test files:
That's it, see the Github for detailed info.
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
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 tosuper
would need to be included in any subclassteardown
method, but this can usually be omitted entirely.If I need to subclass
MyTest
further (e.g. for integration tests) I include its ownsetup
&teardown
methods with calls tosuper
so it goes right up the inheritance tree.I found my mistake ,may be it helps someone else ..
I should write DatabaseCleaner.start in setup of every model test where setup is defined, as i am overwriting setup method in every test file.
If for whatever reason you don't want to add the 'minitest-around' gem (to have more than one setup and teardown method), you can do this in your
test_helper.rb
...