4

Is there a way to prevent Rails from clearing the test database prior to running the test? I want to use a copy of my production database for testing so I need to prevent rails from clearing out the data every time.

There is quite a bit of data so I would like to avoid using fixtures if possible since I'm assuming it would take a long time to populate the db every time.

Thanks, Mike

hoitomt
  • 670
  • 1
  • 6
  • 16
  • 1
    The whole point of testing is to have a database filled with predictable data that doesn't change from one test to the next. By using production data, you lose that benefit. I would really consider using something like `FactoryGirl` to mock up database data for you. – iwasrobbed Jul 11 '11 at 05:21

2 Answers2

6

You can avoid it by running the tests manually

ruby -Itest test/unit/some_test.rb

It is the rake task which does the test db recreation (you can run it manually like so)

rake db:test:prepare

But my suggestion is that you're doing it wrong. The general idea in testing is that you know the state of the database, and therefore know what to expect from a function.

eg.

test "search_by_name" do
  expected = User.all.select{|u| u.name =~ /arthur/i}
  assert_equal expected, User.search_by_name("Arthur")
end

is a fine test however, if you don't know the state of the db, how do you know there is an arthur?

The test above would pass in three bad cases;

  1. there are no User records
  2. all Users are called "Arthur"
  3. there are no users called arther.

So its better to create a false reality, where we know the state of the database.

We want;

  1. at least one user with the name "Arthur"
  2. at least one user with the name "Arthur" as part of another word
  3. at least one non-Arthur user.

a better test, assuming the db is empty, and using factory girl, may be.

test "search_by_name" do
  expected = [
    Factory.create(:user, :name => "Arthur"),
    Factory.create(:user, :name => "MacArthur")
  ]
  not_expected = [Factory.create(:user, :name => "Archer")]
  assert_equal expected, User.search_by_name("Arthur")
end
Matthew Rudy
  • 16,724
  • 3
  • 46
  • 44
  • This didn't work. The ruby -Itest... command deleted the data from my tables. The schema remained intact but the data was removed. However your point regarding known data is well taken. I'm using the test for UI verification right now so I want to use production data so that I see (and test) what the user sees. But a better way may be to just get the tables I need, create fixtures/seeds and do it that way. Thanks for the thorough answer, I appreciate it – hoitomt Jul 11 '11 at 03:01
0

Let me preface this by saying you generally don't want to use production data for testing. That being said...

You could load "seed" data but make sure you don't have any fixtures for it otherwise it will get deleted for every test run.

See this answer for ways to automatically seed data.

Community
  • 1
  • 1
Dty
  • 12,253
  • 6
  • 43
  • 61