我有一个表单,当用户提交带有单个名称字段的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 ==)
UPDATE:刚刚在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
答案 0 :(得分:2)
关键是告诉rspec在做任何期望之前等待ajax调用完成。这是我用过的解决方案的一篇很棒的文章。
Thoughtbot - 自动等待ajax wioth capybara
http://robots.thoughtbot.com/automatically-wait-for-ajax-with-capybara""
答案 1 :(得分:0)
以防其他人偶然发现,而不是使用睡眠,您可以根据UI本身进行测试。如果您使用have_css或找到匹配器,Capybara将等待该元素重新加载,如下所示:
期待(页面).to have_css(“#form-page-two”,可见::可见)#这将强制测试等待ajax调用
Capybara.automatic_reload不能设置为false。 (默认为true)
此策略将缩短测试套件的运行时间;如果测试只花了2或3秒钟加载它只会等待那么长(不是10)。
但是,由于间歇性故障,写入会令人沮丧。为避免这种情况,您可能需要提高等待时间设置。
Capybara.default_max_wait_time = 10
https://github.com/teamcapybara/capybara#asynchronous-javascript-ajax-and-friends