Rspec 测试因奇怪原因失败

Rspec test fails for a strange reason

我有以下 RSpec 测试:

describe 'regular user' do
  let!(:organization) { FactoryGirl.create(:full_organization) }
  let(:user) { create(:user, organization: organization) }

  context 'no access' do
    before do
      sign_in user
      binding.pry # debug
      get(suggestions_path)
    end

    it { expect(response).to have_http_status(:redirect) }
  end
end

如果我 运行 它没有其他测试它工作正常,但如果我 运行 所有测试它会失败。我不知道它会受到怎样的影响。我有具有以下设置的 DatabaseCleaner:

  config.before(:all) do
    DatabaseCleaner.clean_with :truncation  # clean DB of any leftover data
    Rails.application.load_seed
  end

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

好的,所以我们在 binding.pry 行,我们有一个用户:

$ user.inspect
#<User id: 15, organization_id: 1, (...params...)>

但是,如果我们键入 get(suggestions_path),此测试将失败并出现此错误:

$ get(suggestions_path)

Module::DelegationError: User#used_trial? delegated to organization.used_trial?, but organization is nil: User id: 38, email: "person482@example.com", organization_id: 16, (...params...) from .../app/models/user.rb:34:in `rescue in used_trial?'

如果我再次运行它,它工作正常:

get(suggestions_path) => 302

这个ID=38的用户不存在,好像被DatabaseCleaner删除了。但是我不知道为什么在我收到(suggestions_path)请求时它仍然存在。

我试过了config.cache_classes = false但还是失败了:(

好的,我已经解决了这个问题。

我已经删除了所有规格,直到我得到一个带有此错误的最小规格集。

然后我尝试逐行删除,直到找到导致此问题的行:那是 sign_in user 行。

我已将以下代码添加到 rails_helper.rb:

  config.after :each do
    Warden.test_reset!
  end

现在可以正常使用了。