Search code examples
ruby-on-railscapybarafactory-botruby-on-rails-5poltergeist

RecordNotFound using Capybara with Poltergeist


I'm getting a RecordNotFound exception when trying to visit a page with Capybara, and it is only happening with js: true (using the Poltergeist driver).

My feature spec looks like this:

  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}"

And when I drop down into byebug I am seeing this:

[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">]>

And in my controller I simply have this:

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

Solution

  • When using any of the JS supporting drivers with Capybara, the application and test are run in separate threads and each maintains their own connection(s) to the database. The default setup for testing in rails uses "transactional" testing which means before each test a database transaction is opened and at the end of the test the transaction is rolled back. This has the effect of never actually committing any of those records to the DB while still allowing any calls using the connection that opened the transaction to see the new records. However when there are multiple connections, anything using the second connection cannot see records created in the first connection since they aren't really in the database. This is mentioned in the Capybara README - https://github.com/teamcapybara/capybara#transactions-and-database-setup

    The easiest solution for this is to install database_cleaner and configure it with the recommended setup - https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example