Capybara不等待factory_girl完成

时间:2013-08-15 14:53:22

标签: ruby-on-rails ruby rspec capybara factory-bot

鉴于以下简单规范:

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

此测试随机失败。页面上没有使用JS,但是Capybara似乎在FactoryGirl创建所有必要的帖子之前访问了neighborhood_path。使用save_and_open_page查看页面时,我可以看到有时并非所有帖子都已创建。

只需在上面添加sleep 1访问neighborhood_path可以解决问题,但这不是解决方案。

我正在使用RSpec,Capybara,Spork和DatabaseCleaner。我还修补了ActiveRecord,以便它使用共享连接。

2 个答案:

答案 0 :(得分:1)

尝试使用此代替背景块:

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

你可以做到

 visit neighborhood_path(neighborhood)

答案 1 :(得分:0)

这是在ApplicationController中:

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

因此,在获取新创建的记录时发生错误。所以将created_at 1.hour.ago添加到了后期工厂。

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

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

有效!