Rspec Capybara测试与Ajax调用未更新记录 [英] Rspec Capybara test with ajax call not updating record
问题描述
我有一个表单,其中当用户提交带有单个名称字段的ajax表单时,将创建一个属于Template对象的记录。所有这些都可以手动正常运行,但是由于某种原因,当我通过rspec测试它时,它告诉我未创建关联。为什么模板对象在这里没有更新?
I have a form where when a user submits an ajax form with a single name field, a record is created that belongs to a Template object. This all works fine manually, but for some reason when I test this via rspec its telling me that the association was not created. Why isn't the template object updated here?
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输出中注意到了这一点
UPDATE: just noticed this in the rspec output
An error occurred in an after hook
ActionView::Template::Error: undefined method `form_sections' for nil:NilClass
所以它告诉我模板对象不存在,那么以后可以比较它吗?
so its telling me that the template object does not exist, then its able to compare it afterwards?
更新2:因此,问题似乎出乎人们的意料,它是在capybara中等待ajax调用完成。我将其添加到规范中,现在可以正常工作,显然我需要将其重新映射为更好的助手之类的东西。
UPDATE 2: So it appears that the issue is waiting for the ajax call to complete in capybara, before expecting. I added this to the spec and it now works, obviously I need to refacotr this to something better like a helper
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调用要完成。这是我使用的解决方案的好文章:
The key is telling RSpec to wait for the ajax call to complete before doing any expectations. This is a great post on the solution that I used:
Thoughtbot:通过Capybara自动等待AJAX
这篇关于Rspec Capybara测试与Ajax调用未更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!