I have an ActiveRecord class, Post.
In my feature spec which runs with Capybara, RSpec and Poltergeist, I created two instances of it with FactoryGirl
FactoryGirl.create(:post, topic: "Blade running")
FactoryGirl.create(:post, topic: "Dreaming of electric sheep")
Which I can immediately verify in the spec:
scenario "Linking to post by tag", js: true do
FactoryGirl.create(:post, topic: "Blade running")
FactoryGirl.create(:post, topic: "Dreaming of electric sheep")
Post.count # => 2
Post.all.all?(&:persisted?) # => true
visit root_path
# more stuff
end
But when on the next line I visit the root path for my app, (which points to the index action in my posts app), the Posts have vanished (along with their associations):
class PostsController < ApplicationController
def index
@posts = Post.all # => []
#stuff
end
# more methods
end
and when I come back out of the controller action, to the test level, they're back:
Post.count # => 2
Post.all.all?(&:persisted?) # => true
visit root_path
Post.count # => 2
Post.all.all?(&:persisted?) # => true
In the specs that don't use JS I don't have this problem - and just removing "js: true" from the scenario fixes it. But since I'm using a part of the site that requires JS, that's not an option.
I would post this on Poltergeist issues, but since I'm doing something pretty fundamental, it feels a lot more likely that I'm doing something wrong than that this part of Poltergeist is broken. What's my mistake?
Versions: Rails is 5.0.0 Poltergeist is 1.10.0 Capybara is 2.8.0 Rspec-Rails is 3.5.1
It sounds like you are using transactional testing which doesn't work with the JS capable drivers because the test and app code are run in different threads. Each of those threads maintains its own database connection, which means one thread cannot see the records created in the other thread until the transaction is committed. With transactional testing the transactions are never committed so the threads cannot see anything created in the other thread. See https://github.com/jnicklas/capybara#transactions-and-database-setup and then configure database_cleaner to use truncation (or deletion) strategy for your JS capable tests - https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example