【发布时间】: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)- 错误会消失吗? -
可以添加
user和organization模特的代码吗?
标签: ruby-on-rails testing rspec database-cleaner