Search code examples
ruby-on-railstestingrspecdatabase-cleaner

Rspec test fails for a strange reason


I have a following RSpec test:

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

It works fine if I run it without other tests, but it fails if I run all the tests. I have no idea how can it be affected. I have DatabaseCleaner with a following setup:

  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

Ok, so we are in the binding.pry line, and we have a user:

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

However if we type get(suggestions_path), this test fails with this error:

$ get(suggestions_path)

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

If I run it again, it works fine:

get(suggestions_path) => 302

This user with ID=38 does not exists, looks like it was deleted by the DatabaseCleaner. However I don't know why it still exists at the moment when I do get(suggestions_path) request.

I have tried config.cache_classes = false but it still fails :(


Solution

  • Ok, I have solved this.

    I have deleted all the specs until I got a minimum set specs with this error.

    Then I tried to remove line-by-line until I found a line that caused this issue: that was sign_in user line.

    I have added a following code to rails_helper.rb:

      config.after :each do
        Warden.test_reset!
      end
    

    It works fine now.