ruby-on-rails - Rspec Capybara 测试与 ajax 调用不更新记录

标签 ruby-on-rails ajax rspec capybara capybara-webkit

我有一个表单,当用户提交带有单个名称字段的 ajax 表单时,会创建一条属于 Template 对象的记录。这一切都可以手动正常工作,但由于某种原因,当我通过 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 调用完成。这是一篇关于我使用的解决方案的精彩帖子:

Thoughtbot: Automatically Wait for AJAX with Capybara

关于ruby-on-rails - Rspec Capybara 测试与 ajax 调用不更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967849/

相关文章:

ruby-on-rails - Rails 中多表单复选框的数据库结构

sql - rails : How to get column value if present in history?

ajax - .NET Core 从 Razor 页面到 Controller 进行 AJAX 调用

javascript - Symfony 和 Ajax 错误 404,Symfony 工具栏中没有错误消息

ruby-on-rails - AXLSX:为 rspec 测试解析 xlsx 文件

ruby-on-rails - Rails 方式 - 命名空间

ruby-on-rails - 当 Rails 应用程序中只有一行包含 bootstrap 时,为什么要使用 ruby​​ gem 进行 bootstrap?

javascript - PHP 通过 Ajax 为来自 Javascript "JSON.stringify"的对象保存在 MySQL 中?

ruby-on-rails - 无法在 ruby​​ rspec 中解析哈希

ruby - 如何在具有通配符的 RSpec 中请求(GET/POST)路由