Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 515
Chen Kinnrot Avatar asked Nov 25 '25 06:11

Chen Kinnrot


1 Answers

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?

like image 182
p.matsinopoulos Avatar answered Nov 27 '25 20:11

p.matsinopoulos