【问题标题】:Rspec and database_cleaner only remove the data added by the testsRspec 和 database_cleaner 只删除测试添加的数据
【发布时间】:2015-10-30 20:00:51
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 尝试将“load_seed”块的config.before :all do 更改为config.before :each do
  • 如果我把它改成 :each 而不是 :all,只有第一个测试会通过,所有其他测试都会失败,说没有找到数据库中的数据。

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


【解决方案1】:

尝试对所有测试使用:truncation

DatabaseCleaner.strategy = :truncation

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

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

【讨论】:

  • 做到了!这解决了我的问题。我一直在尝试调试我的种子,但没有出现任何错误。但是这个 sn-p 使它起作用了。感谢您抽出宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 2013-01-14
  • 2018-01-23
相关资源
最近更新 更多