Where does Rails store data created by storing activerecord objects during tests?

Where does Rails store data created by storing activerecord objects during tests?

I thought I knew the answer to this question: obviously, in the _test database. But it seems that this is not true !

I used this system to check what happens with saved ActiveRecord data during rspec tests:

$ rails -d mysql test

$ cd test

$ nano config / database.yml ...

... create mysql databases test_test, test_development, test_production

$ script / generate rspec

$ script / generate rspec_model foo

change foo migration:

  class CreateFoos 

$ rake db: migrate

edit spec / models / foo_spec.rb:

  require File.expand_path (File.dirname (__ FILE__) + '/../spec_helper')

 describe Foo do
   before (: each) do
     @valid_attributes = {
       : bar => 12345
     }
   end

   it "should create a new instance given valid attributes" do
     foo = Foo.new (@valid_attributes)
     foo.save
     puts "sleeping ..."
     sleep (20)
   end
 end

$ rake spec

When you see "sleeping ...", change to another open terminal with a mysql session conneted to the test_test database and do:

mysql> select * from foos; Empty set (0.00 sec)

Why does the mysql session not show records in the test_test database during validation?

+6
ruby database ruby-on-rails testing rspec
source share
3 answers

Elements in the test database are erased by default after each design test run. This is to ensure that each of your tests has its own sandbox for playback, which does not cause any interaction with the tests in front of it.

Again, this is by design. You do not need tests that control the same data set (or rely on synchronous execution), because there is no guarantee that the order will be executed.

However, I believe that if you modify the test / test_helper.rb file, say this:

self.use_transactional_fixtures = false 

instead

 self.use_transactional_fixtures = true 

This will save the data in the test database.

SEE ALSO: My advice is specifically designed to work with Test :: Unit, not RSpec. However, I think there is a similar setting for your spec_helper.rb that you should look for.

+13
source share

"But why does the mysql query not show data in the database during test execution?"

Because it is in a transaction. If you turn off transaction lights, your tests will run much slower than before.

+3
source share

You can observe the addition of records to the test database with:

 tail -f log/test.log 

You should see the transactions performed during the execution of the tests.

+1
source share

All Articles