Ruby on Rails - Testing Database

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

There is quite a lot of data, so I would like to avoid using fixtures if possible, as I assume it will take a long time to populate db every time.

Thanks Mike

+4
source share
2 answers

You can avoid this by running tests manually.

ruby -Itest test/unit/some_test.rb 

This is a rake task that does test db recreation (you can run it manually like this)

 rake db:test:prepare 

But my suggestion is that you do it wrong. The general idea in testing is that you know the state of the database and therefore know what to expect from the 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 

- a subtle test however, if you do not know the state of db, how do you know what arthur is?

The test above will pass in three bad cases;

  • no user entries
  • all users are called "Arthur"
  • There are no users called arther.

Therefore, it is better to create a false reality, where we know the state of the database.

We want:

  • at least one user named "Arthur"
  • at least one user named Arthur as part of another word
  • at least one non Arthur user.

better test if db is empty and using factory girl maybe.

 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 
+6
source

Let me state this by saying that you do not want to use production data for testing at all. It is said ...

You can load the β€œseed” data, but make sure that you don’t have any devices, otherwise it will be deleted for each test run.

See this answer for ways to automatically sort data.

0
source

All Articles