RecordNotFound 将 Capybara 与 Poltergeist 结合使用

RecordNotFound using Capybara with Poltergeist

我在尝试使用 Capybara visit 页面时遇到 RecordNotFound 异常,并且它只发生在 js: true(使用 Poltergeist 驱动程序)时。

我的功能规范如下所示:

  context 'existing submissions' do
    background do
      @problem = create(:problem)
      @input = create(:input, problem: @problem)
    end
    scenario 'goes back and edits', js: true do
      visit "/problems/#{@problem.id}/#{@input.lens}"

当我进入 byebug 时,我看到了这个:

[27, 36] in /Users/danielklasson/third_space/spec/features/user_completes_solving_process_spec.rb
   30:     scenario 'goes back and edits', js: true do
   31:       byebug
=> 32:       visit "/problems/#{@problem.id}/#{@input.lens}"
(byebug) visit "/problems/#{@problem.id}/#{@input.lens}"
{"status"=>"success"}
(byebug)
*** ActiveRecord::RecordNotFound Exception: Couldn't find Problem with 'id'=1

nil
(byebug) Problem.all
#<ActiveRecord::Relation [#<Problem id: 1, name: "My Problem", created_at: "2017-01-25 15:35:12", updated_at: "2017-01-25 15:35:12">]>

在我的控制器中我只有这个:

@problem = Problem.find(params[:id])

在 Capybara 中使用任何支持 JS 的驱动程序时,应用程序和测试 运行 在单独的线程中,每个线程都维护自己与数据库的连接。 rails 中的默认测试设置使用 "transactional" 测试,这意味着在每次测试之前都会打开一个数据库事务,并在测试结束时回滚该事务。这具有永远不会实际将任何这些记录提交到数据库的效果,同时仍然允许使用打开事务的连接的任何调用来查看新记录。然而,当有多个连接时,任何使用第二个连接的东西都看不到在第一个连接中创建的记录,因为它们实际上并不在数据库中。 Capybara README 中提到了这一点 - https://github.com/teamcapybara/capybara#transactions-and-database-setup

最简单的解决方案是安装 database_cleaner and configure it with the recommended setup - https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example