我有一个贯穿整个用户流程的功能/集成规范。在该用户流程结束时,应用程序中的一个页面将显示我的 Postgres 数据库中的一些记录。当我自己运行测试时,它通过了。自从 selenium 驱动程序打开 firefox: 以来,我可以通过各个步骤看到它正确保存Capybara.current_driver = :selenium
。然而,当它在一堆控制器规范之后运行时,这个规范经常失败,几乎可以预见。在这些控制器规范中,我正在做的唯一有趣的事情是运行这个登录功能:
module DeviseMacros
def login_user
before(:each) do
@request.env['devise.mapping'] = Devise.mappings[:user]
user = create(:user_with_active_account)
sign_in user
end
end
end
所以我这样称呼它:
describe AwesomeController do
login_user
it 'responds with 200' do
get :new
expect(response.status).to eq 200
end
end
当在控制器规范之后运行时,我可以立即看到测试将失败,因为某些 UI 元素应该根据数据库中的内容出现,并且显然它们不存在。
我的 DatabaseCleaner 策略如下:
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
通过反复试验我改变了
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
到
config.before(:each) do
DatabaseCleaner.strategy = :truncation
end
和沃拉,它通过了。当然,现在测试套件占用了 2 倍以上的时间。
我已经标记了我的所有:selenium
测试,js: true
以确保:truncation
用于它们,但这并不重要,因为:selenium
已经在驱动这些。然而,最重要的是,在这些控制器规范之后,此功能规范仍然失败。
我还应该去哪里寻找?如何进行调试?
我在这里唯一可能与之相关的独特之处是:
# In spec/support/shared_db_connection.rb
# https://gist.github.com/josevalim/470808
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || retrieve_connection
end
end
# Forces all threads to share the same connection. This works on
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
任何有关如何进行调试的建议或想法将不胜感激。
如果您有任何其他问题,请提出。谢谢
更新:2016 年 6 月 1 日
导致失败的确切代码行是:
module DeviseMacros
def login_user
before(:each) do
@request.env['devise.mapping'] = Devise.mappings[:user]
user = create(:user_with_active_account)
sign_in user # <----- THIS GUY RIGHT HERE! When removed, the ControllerSpec fails but the integration test passes.
end
end
end
因此,出于某种原因,使用此控制器规范(使用策略)访问数据库似乎会:transaction
影响功能规范(使用:truncation
策略)。
我正在争论在尝试验证设计用户时根本没有在控制器规范中访问数据库,这对我来说很酷,但我觉得它不应该是这样的。如果我确实希望能够使用该sign_in
方法,有关如何进行的任何想法?
谢谢