我有一个表单,当用户提交带有单个名称字段的 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 调用完成。这是一篇关于我使用的解决方案的精彩帖子:
关于ruby-on-rails - Rspec Capybara 测试与 ajax 调用不更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967849/