Chen Kinnrot
Chen Kinnrot

Reputation: 21015

Rails unit tests: Define a general setup method that will run before every test

I want to clear my database before each test I'm running. Where should I put the script for achieving this behavior?

Upvotes: 3

Views: 3452

Answers (1)

p.matsinopoulos
p.matsinopoulos

Reputation: 7810

Though I cannot imagine why you might want to do this, maybe you can try this one: https://github.com/bmabey/database_cleaner

In any case, the statements that can be called before every test should be put in a call to setup:

setup do
    # statements executed on start of every test
end

UPDATE: To explain a little bit more:

One thing you can do is inside your test_helper.rb file:

class ActiveSupport::TestCase

  ### Common setup for all tests ###
  setup do
      # write code to clean up your database here
  end

end

Then in your actual test files, in which you have test classes deriving from ActiveSupport::TestCase you only have to require 'test_helper'.

In that way, before every test that you ever run, the setup code will be executed.

Does this explain a little bit more what I have written in my first answer?

Upvotes: 7

Related Questions