运行之前rspec清理数据库 [英] rspec clean database before running

查看:89
本文介绍了运行之前rspec清理数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Sinatra项目中使用RSpec。我正在测试运行 after_find 钩子以初始化一些值的模型。我需要在每次运行前擦除数据库,并在进行一些搜索之后,我的spec帮助程序文件如下所示:

I'm using RSpec in a Sinatra project. I'm testing a model which runs an after_find hook to initialize some values. I need to wipe the database before every run, and after some searching around, my spec helper file looks like this:

require "pry"
require "factory_girl_rails"
require "rspec-rails"

FactoryGirl.find_definitions

ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

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

我遇到以下错误:

undefined method `use_transactional_fixtures=' for #<RSpec::Core::Configuration:0x007fc1c89397e8> (NoMethodError)`

我查看了RSpec :: Core :: Configuration的文档,唯一提及 use_transactional_fixtures = 的位置特别声明了特定于轨道的位置。我已经安装了 rspec-rails gem,所以我不知道为什么它不使用它。在规范帮助文件中甚至需要它。

I looked up the documentation for RSpec::Core::Configuration and the only mention of use_transactional_fixtures= is where it specifically states that it's rails specific. I have the 'rspec-rails' gem installed, so I don't know why it's not using it. I'm even requiring it in the spec helper file.

我最初的想法是创建一个运行db:drop,db:create和db:migrate的Rakefile,然后进行测试,但是我希望有一个像 use_transactional_fixtures =

My initial thought was to just create a Rakefile that runs db:drop, db:create, and db:migrate and then the tests, but I'm hoping there's a slightly easier way like use_transactional_fixtures=

推荐答案

我使用数据库清洁程序。这是我在 spec_helper.rb 中(旧的!)

I use Database Cleaner to do this. Here's something I have in a spec_helper.rb (an old one!)

RSpec.configure do |config|
  # Clean up the database
  require 'database_cleaner'
  config.before(:suite) do
    DatabaseCleaner.orm = "sequel"
    DatabaseCleaner.clean_with :truncation, {:only => %w{LIST OF TABLES HERE} } 
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each, :database) do
    # open transaction
    DatabaseCleaner.start
  end

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

我也倾向于从开发中保留单独的测试数据库,只是为了速度并使我的生活更轻松。

I also tend to keep a separate test database from development, just for speed and to make my life easier.

这篇关于运行之前rspec清理数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆