Rails在哪里存储通过在测试期间保存activerecord对象而创建的数据?
我以为我知道这个问题的答案:显然在 _test数据库中。但看起来这是不正确!
我使用这个系统来测试在rspec测试期间保存的ActiveRecord数据发生了什么:
$ rails -d mysql test
$ cd test
$ nano config / database.yml ...
...创建mysql数据库test_test,test_development,test_production
$ script / generate rspec
$ script / generate rspec_model foo
编辑Foo迁移:
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)
为什么mysql会话在测试运行时不显示test_test数据库中的任何记录?
答案 0 :(得分:13)
在每次测试运行后,默认情况下,测试数据库中的项目都会被删除。这样做是为了确保您的每个测试都有自己的沙箱,不会导致与之前的测试发生任何交互。
同样,这是设计的。您不希望测试操作同一组数据(或依赖于同步执行),因为无法保证执行顺序。
但是,我相信如果您修改test / test_helper.rb文件来说明:
self.use_transactional_fixtures = false
而不是
self.use_transactional_fixtures = true
它将导致测试数据库中的数据保持不变。
另外:我的建议是专门设计用于Test :: Unit,而不是RSpec。但是,我想你应该寻找类似的spec_helper.rb设置。
答案 1 :(得分:3)
“但是为什么mysql查询在测试运行时没有显示数据库中的数据?”
因为它在交易中。如果您关闭事务性灯具,您的测试运行速度会比之前慢得多。
答案 2 :(得分:1)
您可以使用以下命令观察添加到测试数据库的记录:
tail -f log/test.log
在测试运行时,您应该看到飞行的交易。