简体   繁体   中英

Capybara does not wait for factory_girl to finish

Given the following simple spec:

require 'spec_helper'

feature 'Feeds', %q{
  In order see the latest content of Buurtlink
  As a user
  I should be able to view a neighborhood or postal_code
} do

  background do
    @neighborhood = FactoryGirl.create(:neighborhood_with_posts)
  end

  scenario 'Visitor views a neighborhood' do
    visit neighborhood_path(@neighborhood)

    find('#header_title').should have_content 'Diemen-Zuid'

    10.times do |index|
      expect(page).to have_text "Title of new post #{index}"
    end
  end

end

This test randomly fails. No JS is used on the page, but Capybara seems to visit the neighborhood_path before FactoryGirl is done creating all necessary posts. When looking at the page using save_and_open_page I can see that sometimes not all posts have been created yet.

Simply adding sleep 1 above visit neighborhood_path fixes the problem, but that's not a solution.

I'm using RSpec, Capybara, Spork and DatabaseCleaner. I also monkey-patched ActiveRecord so that it uses a shared connection.

Try this instead of your background block:

let!(:neighborhood){FactoryGirl.create(:neighborhood_with_posts)}

and you can do

 visit neighborhood_path(neighborhood)

This was in the ApplicationController:

def load_posts_after_current_time
  session[:load_posts_after] = DateTime.now unless params[:page].present?
end

Therefore, errors occurred when fetching newly created records. So added created_at 1.hour.ago to the post factory.

  factory :post do
    user { FactoryGirl.create(:user) }
    created_at 1.hour.ago

    factory :neighborhood_post do
      association :postable, factory: :_neighborhood_post
    end
  end

It works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM