【问题标题】:Rspec test fails for a strange reasonRspec 测试因奇怪的原因而失败
【发布时间】:2017-02-20 22:44:03
【问题描述】:

我有以下 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?委托给 organization.used_trial?,但组织为零:用户 ID:38, 电子邮件:“person482@example.com”,organization_id:16,(...参数...) 来自 .../app/models/user.rb:34:in `rescue in used_trial?'

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

获取(建议路径) => 302

此 ID=38 的用户不存在,似乎已被 DatabaseCleaner 删除。但是我不知道为什么在我做 get(suggestions_path) 请求时它仍然存在。

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

【问题讨论】:

  • 如果您将let(:user) 更改为let!(:user) - 错误会消失吗?
  • 可以添加userorganization模特的代码吗?

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


【解决方案1】:

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

我已经删除了所有的规范,直到我得到一个出现此错误的最小设置规范。

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

我在 rails_helper.rb 中添加了以下代码:

  config.after :each do
    Warden.test_reset!
  end

现在可以正常使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多