1

我希望能够始终访问我的测试数据库中的种子数据。我知道如果以这种方式设置,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 添加的数据?而不是种子?或者甚至可能告诉它不要删除某些表?

任何帮助,将不胜感激。

4

1 回答 1

4

尝试使用:truncation以下所有测试:

DatabaseCleaner.strategy = :truncation

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

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

于 2015-10-30T22:23:38.050 回答