Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails测试数据库赢得';t擦拭_Ruby On Rails_Database_Postgresql_Ruby On Rails 3_Rspec - Fatal编程技术网

Ruby on rails rails测试数据库赢得';t擦拭

Ruby on rails rails测试数据库赢得';t擦拭,ruby-on-rails,database,postgresql,ruby-on-rails-3,rspec,Ruby On Rails,Database,Postgresql,Ruby On Rails 3,Rspec,我正在运行rails 3.0.3,并使用RSpecRails 2.4.1和postgresql数据库。每当我运行RSpec测试时,数据都会保留在末尾。有人知道如何让rails或rspec在每次使用之间擦除测试环境的数据吗 请告诉我是否有任何进一步的信息,可以使回答我的问题更容易 谢谢Tristan安装数据库\u cleaner gem,然后将其添加到spec\u helper.rb Spec::Runner.configure do |config| config.before(:suit

我正在运行rails 3.0.3,并使用RSpecRails 2.4.1和postgresql数据库。每当我运行RSpec测试时,数据都会保留在末尾。有人知道如何让rails或rspec在每次使用之间擦除测试环境的数据吗

请告诉我是否有任何进一步的信息,可以使回答我的问题更容易


谢谢
Tristan

安装数据库\u cleaner gem,然后将其添加到spec\u helper.rb

Spec::Runner.configure do |config|

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

使用事务性示例在每次测试运行后回滚数据

RSpec.configure do |config|
  config.use_transactional_examples = true
end

另一种可能是,我刚才提到的,使用了错误的
before

我意外地将
之前的
块设置为
所有
,而不是
每个

before :all do
  user = FactoryGirl.create(:user)
  sign_in user
end
这导致
用户
在整个
rspec
运行期间在数据库中停留,从而导致验证冲突

相反,在
之前的
应该是
每个
,以便通过
rspec
运行保持一切清洁:

before :each do
  user = FactoryGirl.create(:user)
  sign_in user
end

如果您犯了这个错误,那么您可能需要在一切恢复正常之前手动清理测试数据库。最简单的方法可能是截断每个表(除了
schema_migrations
)。

在运行之间清理测试数据库不需要任何额外的gem。在spec_helper.rb文件中,按如下方式配置rspec:

RSpec.configure do |c|
  c.around(:each) do |example|
    ActiveRecord::Base.connection.transaction do
      example.run
      raise ActiveRecord::Rollback
    end
  end
end

我相信数据是在你运行测试之前清除的,而不是之后。嘿,Cam。对不起,那可能是对的,但现在两件事都没有发生。嘿,谢谢你,鲍比。默认情况下,每次运行rspec时,测试数据库不应该开始为空吗?嘿,Tristan,应该为空,但是当数据在测试之间徘徊时,会出现一些奇怪的情况。我还相信,如果您使用
rake
调用您的规范,它将在您的规范之前运行
db:test:prepare
。嗨,Deepak。我的spec\u helper文件中已经有了这个设置,我的rspec脚本是“require”ing spec\u helper。我在rspec 2.8.0中得到了
未定义的方法“use\u transactional\u examples=”
。此方法是否有新名称?是。它现在是
use\u transactional\u fixture
这在Rails 5.1.6中对我有效,但我必须将它放在Rails\u helper.rb文件中,而不是spec\u helper文件中。