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

Rspec and database_cleaner only remove the data added by the tests

我希望能够始终访问我的测试数据库中的种子数据。 我知道 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 命中最后一个测试,它就不再具有数据库中的权限。

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

如有任何帮助,我们将不胜感激。

尝试使用 :truncation 进行所有测试:

DatabaseCleaner.strategy = :truncation

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

您的种子也可能有问题,而 DatabaseCleaner 没有。您应该使用 puts 语句或调试器(例如 pry-byebug)在失败的测试中调试数据库状态。