Ruby on rails 带有ajax调用的Rspec Capybara测试未更新记录

Ruby on rails 带有ajax调用的Rspec Capybara测试未更新记录,ruby-on-rails,ajax,rspec,capybara,capybara-webkit,Ruby On Rails,Ajax,Rspec,Capybara,Capybara Webkit,我有一个表单,当用户提交一个带有单个名称字段的ajax表单时,将创建一个属于模板对象的记录。这一切都可以手动进行,但由于某种原因,当我通过rspec测试时,它告诉我关联没有创建。为什么模板对象没有在这里更新 describe "edit page" do before(:each) do visit edit_admin_template_path(template) end context "form sections", js: true do it "al

我有一个表单,当用户提交一个带有单个名称字段的ajax表单时,将创建一个属于模板对象的记录。这一切都可以手动进行,但由于某种原因,当我通过rspec测试时,它告诉我关联没有创建。为什么模板对象没有在这里更新

describe "edit page" do
  before(:each) do
    visit edit_admin_template_path(template)
  end

  context "form sections", js: true do  
    it "allows admin to create one" do
      find("#btn-add-section").click
      within('#new_form_section') do
        fill_in 'Name', with: "Personal Info"
        click_button "Create Section"
      end
      expect(template.form_sections.length).to eq(1)
    end
  end
end
这就是我的失败

Failure/Error: expect(template.form_sections.length).to eq(1)

   expected: 1
        got: 0

   (compared using ==)
更新:刚刚在rspec输出中注意到了这一点

An error occurred in an after hook
    ActionView::Template::Error: undefined method `form_sections' for nil:NilClass
所以它告诉我模板对象不存在,那么它以后能够比较它吗

更新2:因此,问题似乎在等待ajax调用在capybara中完成,然后才出现。我把它添加到规范中,现在它可以工作了,显然我需要将它重新编译成更好的东西,比如助手

it "allows admin to create one" do
  find("#btn-add-section").click
  within('#new_form_section') do
    fill_in 'Name', with: "Personal Info"
    click_button "Create Section"
  end
  sleep(10) #this waits for the request to complete
  expect(template.form_sections.length).to eq(1)
end

关键是告诉RSpec在执行任何预期操作之前等待ajax调用完成。这是一篇关于我使用的解决方案的精彩文章:


以防万一其他人偶然发现这一点,而不是使用睡眠,您可以基于UI本身进行测试。如果使用have_css或find matchers,水豚将等待该元素重新加载,如下所示:

期望(第页)有_css(#form page two,visible::visible)#这将迫使测试等待ajax调用

Capybara.automatic_reload不能设置为false。(默认为true)

此策略将减少测试套件的运行时间;如果加载测试只需2或3秒,它将只等待那么长的时间(不是10秒)

然而,由于间歇性故障,编写可能会令人沮丧。为了避免这种情况,您可能需要增加等待时间设置

Capybara.default\u max\u wait\u time=10


不过,这是我的想法。如果您有来自AJAX请求的“x”元素渲染,并且您有等待AJAX实现,该怎么办。这很好,但不是很详细,是吗?我们目前正在与将发布中断的功能测试进行争论,但要真正找到中断的原因有点困难,因为wait_for_ajax错误只是二进制的。你过去是怎么处理的?