Rspec和database_cleaner仅删除测试添加的数据

时间:2015-10-30 20:00:52

标签: ruby-on-rails rspec database-cleaner

我希望能够始终在我的测试数据库上访问我的种子数据。 我知道如果以这种方式设置,database_cleaner将删除所有内容。

我尝试删除所有内容然后重新加载种子,但是当我尝试在测试中使用js:true时,种子永远不会被加载,所以我得到错误,说数据不存在。

我的spec_helper.rb

RSpec.configure do |config|
  # before the entire test suite runs, clear the test database out completely
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end
  # sets the default database cleaning strategy to be transactions (very fast)
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end
  # For these types of tests, transactions won’t work. We must use truncation
  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end
  # hook up database_cleaner around the beginning and end of each test, telling it to execute whatever cleanup strategy we selected beforehand.
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  # reload the seed so we have data to play with
  end
  config.before :all do
    Rails.application.load_seed
  end
end

在我的view_spec中,我有类似的东西

require 'spec_helper'
describe 'my/path', type: :view do
  before do
    @user = create(:user)
    @user.permissions << Permission.first
    login_as(@user)
    visit my_path
  end
  it 'should have a valid user, just for kicks' do
    @user.should be_valid
  end
  it 'should be in the path i said' do
    expect(current_path).to eq(my_path)
  end
  describe 'click submit button', js: true do
    it 'should take me to a different path' do
      click_link('button_1')
      expect(current_path).to eq(my_new_path)
    end
  end
end

前两个测试将运行并且可以创建该用户,但是一旦它使用js:true命中最后一个测试,它就不再具有数据库中的Permission。

有没有办法告诉database_cleaner只删除rspec添加的数据?而不是种子? 或者甚至可能告诉它不删除某些表格?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

Try to use :truncation for all tests with:

DatabaseCleaner.strategy = :truncation

RSpec.configure do |config|
  config.before(:each) do
    DatabaseCleaner.clean
    Rails.application.load_seed
  end
end

There also may be an issue with your seeds and not with DatabaseCleaner. You should debug your database state right in the failing test using puts statements or debugger (e.g. pry-byebug).